javascript - 如何从传递给 react 组件的 Prop 设置状态?

标签 javascript reactjs

我有这个简单的组件,initialPlayers 属性被传递给 App 组件。

import React from 'react';
import ReactDOM from 'react-dom';

var PLAYERS = [
  {
    name: "xyz",
    score: 123
  }
];

// App component
class App extends React.Component {

 constructor() {
   super();
 }

 componentDidMount() {
   this.state = {
     players: this.props.initialPlayers
   }
 }

 render() {    
   return(
     <div>
       <Header players={this.state.players} />
     </div>
   );
 }
}

// Render component
ReactDOM.render(<App initialPlayers={ PLAYERS }/>, 
document.getElementById('root'));

在控制台中出现此错误,并且无法将值作为 {this.state.players} 传递给 Header 组件。有什么想法吗?

Uncaught TypeError: Cannot read property 'players' of null
at App.render (bundle.js:14379)
at bundle.js:20173
at measureLifeCyclePerf (bundle.js:19452)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (bundle.js:20172)
at ReactCompositeComponentWrapper._renderValidatedComponent (bundle.js:20199)
at ReactCompositeComponentWrapper.performInitialMount (bundle.js:19739)
at ReactCompositeComponentWrapper.mountComponent (bundle.js:19635)
at Object.mountComponent (bundle.js:4667)
at ReactCompositeComponentWrapper.performInitialMount (bundle.js:19748)
at ReactCompositeComponentWrapper.mountComponent (bundle.js:19635)

最佳答案

将设置玩家行移动到您的构造函数()中:

constructor(props) {
  super(props);
  this.state = {
    players: this.props.initialPlayers
  };
}

关于javascript - 如何从传递给 react 组件的 Prop 设置状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43621003/

相关文章:

reactjs - 不工作 : require ('react/addons' )

javascript - 滚动到隐藏的输入

javascript - 如何在单个容器中创建和管理多个 iframe?

javascript - 使用 JavaScript 仅替换 DIV 中的文本内容

javascript - 我应该等待 ajax 完成重定向页面吗?

reactjs - Redux 表单 Typescript 传递自定义 Prop

javascript - 删除倒数第二个索引后的其余字符串

javascript - 在两行中 chop 名称列表

javascript - 如何区分通过鼠标滚动和在 JavaScript 中以编程方式滚动?

javascript - 超时后在无状态组件中执行功能