【问题标题】:React Context Consumer does not update (but Provider does)React Context Consumer 不会更新(但 Provider 会更新)
【发布时间】: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


    【解决方案1】:

    Info 组件似乎不在VG 之下。

    这行得通:

    <MyProvider>
      <MyConsumer />
    </MyProvider>
    

    这不是:

    <MyProvider>
      <SomeOtherNode />
    </MyProvider>
    <MyConsumer />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2020-07-18
      • 2021-10-05
      • 1970-01-01
      • 2021-06-13
      • 2017-10-09
      相关资源
      最近更新 更多