【发布时间】:2019-07-30 18:50:30
【问题描述】:
我有一个相当简单的应用程序,其中包含几个组件,其中 2 个需要具有单向状态共享。它们都嵌套得很远,所以我正在尝试使用 ReactContext。
React 16.8.23
问题是,虽然 Provider 确实更新了状态,而 Context 也在改变它 - Consumer 根本没有改变。
以下是有问题的两个组件:
提供者
class VG extends Component {
constructor(props) {
super(props);
this.state = {
id:[24]
};
}
onSelect = (_, value) => {
this.setState(value)
}
render() {
return (
<ListingContext.Provider value={this.state}>
<ContainerDimensions>
{ ({ width, height }) => {
spec.width = width;
spec.height = height;
return <Vega spec={spec} onSignalSelectPoint={this.onSelect}/>
}}
</ContainerDimensions>
</ListingContext.Provider>
);
}
}
和消费者
class Info extends Component {
render() {
return (
<ListingContext.Consumer>
{
selected => (
<Paper elevation={10} style={{"margin":`20px`, "height":`calc(100% - 64px)`}} >
<Typography variant="h5" component="h3">
Here is the listing id: {selected.id[0]}
</Typography>
<Typography component="p">
Listing's info
</Typography>
</Paper>
)
}
</ListingContext.Consumer>
)
}
}
export default Info;
这里,“Info”组件无论如何都保持上下文的默认值
【问题讨论】:
标签: reactjs react-context