以下是我的应用程序 struct 的伪代码示例.我正在try 与Reaction上下文全局共享状态,但在顶层更新状态会导致子组件重新呈现和重置状态(我认为)的问题.
// 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 {
...
}
}
我的问题:
这是一个可以接受的应用程序 struct ,还是有问题?我可以做些什么来持久子组件网络中的状态,或者我需要以某种方式将共享状态移出App.js吗?