gpt4 book ai didi

javascript - useReducer 不同步更新状态的问题

转载 作者:行者123 更新时间:2023-11-29 10:27:28 26 4
gpt4 key购买 nike

根据 React 文档:

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

1. 谁能解释一下为什么 useReducer 没有同步更新状态?

const reducer = (state, action) => {
if( action.type === 'ADD_VALUE') {
console.log(`STATE IN REDUCER`, [...state, action.path]) // => ["1.1"]
return [...state, action.path]
}
}

const [state, dispatch] = useReducer(reducer, [])

<input type="button" onClick={() => {
dispatch({ type: 'ADD_VALUE', path: "1.1"})
console.log(`STATE`, state) // => []
// here i want to do some stuff based on the lastest updated state (["1.1"] and not [])
// for example dispatch an action with redux
}}/>

2. 我如何根据最新更新的状态(["1.1"] 而不是 [] 做一些事情(发送 redux Action ) ) ?

最佳答案

使用useEffect 来正确访问状态。如果您希望在满足特定条件时调用某些东西,您可以添加一些安全保护措施。

如果你想跨组件访问你的 reducer,你可以使用 Context API 存储 reducer。看下面的例子。您可以看到 reducer 被注入(inject)到父组件的 Context 中,然后是两个子组件 a) 调度一个 Action b) 从 Action 接收更新。

<强>1。跨多个组件使用的 context reducer 示例

import React from "react";
import ReactDOM from "react-dom";

const Application = React.createContext({
state: null,
dispatch: null
});

function ActionComponent() {
const { dispatch } = React.useContext(Application);
return (
<div>
<div>Action Component</div>
<button onClick={() => dispatch("lol")}>Do something</button>
</div>
);
}

function ListenerComponent() {
const { state } = React.useContext(Application);
React.useEffect(
() => {
console.log(state);
},
[state]
);
return <div>Listener Component</div>;
}

function App() {
const [state, dispatch] = React.useReducer(function(state = [], action) {
return [...state, action];
});
return (
<Application.Provider value={{ state, dispatch }}>
<div className="App">
<ActionComponent />
<ListenerComponent />
</div>
</Application.Provider>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

<强>2。不使用 Application Context 的本地 reducer 示例

const reducer = (state, action) => {
if( action.type === 'ADD_VALUE') {
return [...state, action.path]
}
}

const [state, dispatch] = useReducer(reducer, [])

React.useEffect(() => {
console.log(state);
}, [state]);

<input type="button" onClick={() => {
dispatch({ type: 'ADD_VALUE', path: "1.1"})
}}/>

关于javascript - useReducer 不同步更新状态的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55301495/

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