我正在开发一个 nextjs 项目,在该项目中我有一个与 pages 文件夹处于同一级别的 helpers 文件夹。
我在 helpers 文件夹中有一个 ts 文件,在这里我想根据最新状态获取最新状态和更新状态
这就是我获取状态的方式
store().getState()
从 store.js 导入 store
我根据之前的状态更新状态
const state = store().getState()
if(!state.currentUser){ // here im checking if state has currentUser
store().dispatch(Action) // here im calling action which will update the state
}
do further operations
这里的问题是我在更新状态后没有从 store().getState()
获取更新的状态。我的管理方式是否正确?如何获取更新的状态?
*EDIT* : Im sending a helper function as a prop to many if my page components. Now that i dont want to touch this , i somehow want to get the updated state and dispatch actions based on the state itself. Note that the hepler function is not a functional component
提前致谢
答案 0 :(得分:1)
问题是你使用的这个 store 不是 React 的一部分,所以 React 不知道数据何时发生变化。你必须创建一种方法让 React 知道数据发生了变化,以便它可以重新渲染你的组件或触发一个动作。 您的商店是否提供订阅更改的方法?如果是这样,你可以在你的组件中做这样的事情(假设你正在使用钩子):
编辑:可重复使用的钩子方式:
export const useStore = () => {
const [storeState, setStoreState] = useState(store().getState());
useEffect(() => {
const subscribeFunc = (newState) => setStoreState(newState));
store().subscribe(subscribeFunc);
return () => {
store().unsubscribe(subscribeFunc);
}
}, [])
return [storeState, store().dispatch]
}
然后在你的组件中
const [storeState, dispatch] = useStore();
// listen to changes of the currentUser and fire actions accordingly
useEffect(() => {
if (!storeState.currentUser) {
dispatch(Action)
}
}, [storeState.currentUser])
初始方式:
// sync the store state with React state
const [storeState, setStoreState] = useState(store().getState());
useEffect(() => {
const subscribeFunc = (newState) => setStoreState(newState));
store().subscribe(subscribeFunc);
return () => {
store().unsubscribe(subscribeFunc);
}
}, [])
// listen to changes of the currentUser and fire actions accordingly
useEffect(() => {
if (!storeState.currentUser) {
store().dispatch(Action)
}
}, [storeState.currentUser])
通过在组件中设置更改状态,React 现在知道数据已更改并会相应地采取行动。
这是一种非常本地化的方法来解释这个概念,但显然最好创建一个可重复使用的钩子,以便在您的应用中为任何商店使用。