【发布时间】:2021-03-01 07:57:10
【问题描述】:
假设我有一个Parent 组件,它提供了一个Context,它是一个Store 对象。为简单起见,假设这个 Store 有一个 value 和一个 update this value
class Store {
// value
// function updateValue() {}
}
const Parent = () => {
const [rerender, setRerender] = useState(false);
const ctx = new Store();
return (
<SomeContext.Provider value={ctx}>
<Children1 />
<Children2 />
.... // and alot of component here
</SomeContext.Provider>
);
};
const Children1 = () => {
const ctx = useContext(SomeContext);
return (<div>{ctx.value}</div>)
}
const Children2 = () => {
const ctx = useContext(SomeContext);
const onClickBtn = () => {ctx.updateValue('update')}
return (<button onClick={onClickBtn}>Update Value </button>)
}
所以基本上Children1会显示值,而在Children2组件中,有一个更新值的按钮。
所以我现在的问题是当Children2 更新 Store 值时,Children1 不会重新渲染。 以反映新值。
堆栈溢出的一种解决方案是here。这个想法是在Parent 中创建一个state 并使用它将context 传递给孩子们。这将有助于重新渲染 Children1 因为 Parent 被重新渲染。
但是,我不想 Parent 重新渲染,因为在Parent 中有很多其他组件。我只想重新渲染Children1。
那么有什么办法可以解决这个问题吗?我应该使用 RxJS 进行响应式编程还是应该更改代码中的某些内容?谢谢
【问题讨论】:
-
也许你可以在这里获得更多信息。 stackoverflow.com/questions/50817672/…
-
updateValue('update')它看起来怎么样?似乎可能存在无法更新正确对象属性的问题。
标签: javascript reactjs typescript reactive-programming react-context