gpt4 book ai didi

javascript - Svelte/Sapper - 无法保存不同路线上 api 响应的数据

转载 作者:行者123 更新时间:2023-11-28 03:04:21 25 4
gpt4 key购买 nike

我一直在尝试在 svelte 中创建一个身份验证系统,注册是一个多步骤过程,因此需要保存第 1 步中的 api 响应并传递,每个步骤都是不同的路线。遇到过 store 很简洁,但不知何故,当使用 get 获取数据时,它只是返回 undefined 。下面是返回相同输出的演示代码。

index.svelte

<script>
import signUpStore from "./hobby-store.js";
let data = {
name: "Rahul",
age: "something"
};
signUpStore.setSignUp(data);

// let result = signUpStore.getSignUp();
// console.log(result); //undefined
</script>

<p>
<strong>
Try editing this file (src/routes/index.svelte) to test live reloading.
</strong>
</p>

关于.svelte

<script>
import signUpStore from "./hobby-store.js";
import { onMount } from "svelte";
let result = signUpStore.getSignUp();
console.log("server side : ", result); //undefined

onMount(() => {
console.log("client side : ", result); // undefined
});
</script>

<p>This is the 'about' page. There's not much here.</p>

爱好商店.js

import {
writable,
get
} from 'svelte/store'

const signUp = writable()

const signUpStore = {
subscribe: signUp.subscribe,
setSignUp: (items) => {
signUp.set(items)
// console.log('items : ', items, signUp)
},
addSignUp: (data) => {
signUp.update(items => {
return items.concat(data)
})
},
getSignUp: () => {
get(signUp)
}
}

export default signUpStore;

只需将此数据保存在 session 或 svelte 或 sapper 提供的任何持久存储中,并在成功操作后重置它。

最佳答案

下面带有日志记录的 session.js 存储示例:

import { writable } from 'svelte/store';
import { deepClone } from './../utilities/deepClone.js';

const newSession = {
a; 0, b: 0, x: 0
};

function sessionStore() {

const { subscribe, set, update } = writable(deepClone(newSession));
let logging = false;

return {
subscribe, // $session...
update: (obj) => {
update(o => { // session.update({a:1, b:2});
const merged = Object.assign(o, obj);
if (logging) console.log('session update', merged);
return merged;
});
},
set: (key, value) => { // session.set('x', 9)
update(o => {
const merged = Object.assign(o, {[key]: value});
if (logging) console.log('session set', merged);
return merged;
});
},
reset: () => { // session.reset()
set(deepClone(newSession));
},
set log(bool) { // setter: session.log = true;
logging = bool === true;
}
};
};
export const session = sessionStore();

示例.svelte

<script>
import { session } from './session.js';

session.log = true;
$: console.log('reactive log', $session);
session.set('x', 10);
session.reset();

<script>

关于javascript - Svelte/Sapper - 无法保存不同路线上 api 响应的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60734045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com