React Context Consumer 不更新(但 Provider 更新)

React Context Consumer does not update (but Provider does)

我有一个相当简单的应用程序,只有几个组件,其中 2 个需要单向状态共享。它们都嵌套得很远,所以我正在尝试使用 ReactContext。

React 16.8.23

问题是,虽然提供者确实更新了状态,上下文也在改变它,但消费者根本没有改变。

这里是有问题的两个组件:

提供商

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" 组件保留上下文的默认值,无论如何

Info 组件似乎不在 VG 下。

这个有效:

<MyProvider>
  <MyConsumer />
</MyProvider>

这不是:

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