关于使用带有React Hook的巨大树状结构列表构建React App和状态管理的问题- 我收到了大量的JSON列表,并且每当通过套接字进行更新或通知时,我都会收到相同的树结构化JSON,其中的小叶节点已更改,并且它将重新呈现整个子组件,我知道使用redux我可以通过仅传递特定状态对象并忽略其他状态对象并将其保存并存储在商店中来构造应用程序,我应该如何使用诸如管理此巨大JSON对象之类的反应挂钩来构造我的组件
答案 0 :(得分:0)
这是一种方法:
将您的大型JSON保存为一个状态,并根据该大型JSON树的特定属性的更改将多个useEffect()
设置为运行。更新每个useEffect()
中与这些属性相关的组件。
function App() {
// THIS IS TO AVOID THE EFFECTS TO RUN ON 1ST RENDER (WHEN STATE IS 1ST CREATED)
const isFirstRender = React.useRef(true);
// THIS IS YOUR BIG JSON TREE
const [deepState, setDeepState] = React.useState({
propA: {
propAA: false
},
propB: {
propBB: false
}
});
// THIS SIMULATES YOUR 1ST SOCKET MSG
React.useEffect(()=>{
setTimeout(
()=>setDeepState((prevState) => ({
propA: {
propAA: false
},
propB: {
propBB: true
}
})),1500);
},[]);
// THIS SIMULATES A 2ND SOCKET MSG
React.useEffect(()=>{
setTimeout(
()=>setDeepState((prevState) => ({
propA: {
propAA: true
},
propB: {
propBB: true
}
})),3000);
},[]);
// THIS WILL UPDATE COMPONENTS THAT CARE ABOUT ONE SPECIFIC DEEP PROPERTY
React.useEffect(()=>{
if (isFirstRender.current === true) {
return;
}
console.log('Deep property propB.propBB has changed to: ' + deepState.propB.propBB);
console.log('Will updateComponents that depend on propB.propBB');
},[deepState.propB.propBB]);
// THIS WILL UPDATE COMPONENTS THAT CARE ABOUT ANOTHER SPECIFIC DEEP PROPERTY
React.useEffect(()=>{
if (isFirstRender.current === true) {
return;
}
console.log('Deep property propA.propAA has changed to: ' + deepState.propA.propAA);
console.log('Will updateComponents that depend on propA.propAA');
},[deepState.propA.propAA]);
// THIS IS TO AVOID THE EFFECTS TO RUN ON 1ST RENDER (WHEN STATE IS 1ST CREATED)
React.useEffect(()=>{
isFirstRender.current = false;
},[]);
return(
<div>Some Component</div>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>