通过上下文传递的状态返回未定义

时间:2020-04-27 16:50:04

标签: javascript reactjs

我正在尝试使上下文正常工作。 我已经添加了它,并且如果我将字符串作为属性传递给状态,它也可以正常工作。但是,我想通过一个道具作为状态。

这可行:

export class DataProvider extends Component {
  constructor(props) {
    super(props);
    this.state = {
      continent: props.continent,
    };
    this.updateState = this.updateState.bind(this);
  }

  updateState() {
    this.setState({ continent: this.props.continent});
  }

  componentDidMount() {
    console.log(this.props.continent);
    this.updateState();
  }

  render() {
    return (
      <DataContext.Provider value={{ state: this.state }}>
        {this.props.children}
      </DataContext.Provider>
    );
  }
}

但这不起作用(导致未定义)

  this.state = {
      continent: this.props.continent,
    };

当我尝试访问它时,结果为“未定义”。

我从名为“非洲”的组件中获得道具,该组件将执行以下操作:

const Africa = ({}) => {
  return (
    <div>
       <DataProvider continent={["Africa"]} /> 
........irrelevant code

它成功传递到我的DataProvider组件。 但是,正如我所说,当我尝试将其作为状态的属性传递时,结果为“未定义”。

class JumbotronPage extends Component {
  static contextType = DataContext;

  render() {
    console.log(this.context)

A(数据提供者),B(非洲),C(超大页) 我不确定是否是因为A和B相互识别。 B和C没有。

因此,每当我从A访问C时,B都会被重新渲染,导致C没有任何状态。这有道理吗?

拜托,请原谅我对React非常绿色和陌生。我希望我有道理。

谢谢

编辑: setState似乎无法正常工作。我将其放入componentDidMount中,现在可以设置字符串状态,但是,一旦将其传递给道具,它就没有定义。

Edit2: 这是我App.js的一部分:

<Route exact path="/Login" component={Login} />

            <Route exact path="/Jumbotron">
              <DataProvider>
                <JumbotronPage />
              </DataProvider>
            </Route>
            <Route exact path="/CreateNewMemories" component={renderForm} />

Edit3: 如果有人有时间耐心看看我的可憎之处,我就创建了要旨。

https://gist.github.com/kalleftw/e79412034eafd29a2e26b1af24149e67

Edi4: 我什至需要设置状态吗?

this.state = {
      continent: props.continent,
    };

当我使用componentDidMount登录时,这似乎起作用。 但是,当我尝试访问组件“ Jumbotron”时,其中的上下文是未定义的。

1 个答案:

答案 0 :(得分:1)

正确的更新状态的方法是使用setState,但这是一个函数。使用this.setState({ ... })而不是this.setState = { ... }

相关问题