gpt4 book ai didi

javascript - React 中未定义上下文值

转载 作者:行者123 更新时间:2023-12-02 23:37:54 25 4
gpt4 key购买 nike

为什么上下文值显示未定义?

src/Context.js:

import React, { Component } from 'react';

const Context = React.createContext();

export class Provider extends Component {
state = { a: 1, b: 2 };
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
);
}
}
export const Consumer = Context.Consumer;

src/country/CountryList.js:

import React, { Component } from 'react';
import { Consumer } from '../../Context';

class CountryList extends Component {
render() {
return (
<Consumer>
{value => {
console.log('val:' + value);
}}
</Consumer>
);
}
}
export default CountryList;

尝试在 CountryList 中传递上下文值,但它显示未定义,无法弄清楚原因。提前致谢

最佳答案

您需要使用 Provider 包装您的 CountryList 组件,即您需要导入 Provider。

import React, { Component } from 'react';
import { Provider,Consumer } from '../../Context';

class CountryList extends Component {
render() {
return (
<Provider>
<Consumer>
{value => {
console.log('val:' + value);
}}
</Consumer>
</Provider>
);
}
}
export default CountryList;

此处为 Stackblitz 示例:https://stackblitz.com/edit/react-143zwt(我只是为了测试而添加。它会给你一些想法。我不会在其中添加此代码。)

关于javascript - React 中未定义上下文值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56211008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com