【发布时间】:2022-12-12 23:10:59
【问题描述】:
这是我的应用程序结构的伪代码示例。我正在尝试与 React 上下文全局共享状态,但在顶层更新状态会导致子组件重新渲染和重置状态(我认为)出现问题。
// My top level where I store the state all other components need
function App() {
const [userData, setUserData] = useState()
const userContext = {
userData,
setUserData
}
return (
<App>
<Context.Provider value={userContext}>
<Child />
<Child />
<Child />
</Context.Context.Provider>
</App>
)
}
// My child component where I want to preserve state
const Child = () => {
const [childState, setChildState] = useState('default value')
// I want to keep this value
setChildState('new value')
// This is causing App.js to re-render, then Child to rerender, and I lose child state. Then on the next render my 'childState' is back to 'default value', when I want it to still be 'new value'
const userContext = useContext(...)
userContext.setUserData('some change to userdata')
return {
...
}
}
我的问题:
这是一个好的应用程序结构,还是有问题?我可以做些什么来将状态保留在 Child componenet 中,还是我需要以某种方式将共享状态移出 App.js?
【问题讨论】:
-
首先,您不允许更新渲染方法中的任何状态,您在
Child中违反了这一点。从举一个合适的例子开始。 -
当父状态发生变化时,子状态将始终卸载,您可以将子状态移动到父/上下文或尝试使用外部状态管理库,如 jotai
-
@super 正如我在问题中所述,它是伪代码。我不想问语法,而是项目结构。
-
@JackA7X 我没有指出语法。我指出了导致您所描述的行为的代码中的结构错误。
标签: reactjs