如何设置传递给反应组件的道具的状态?

时间:2017-04-25 21:08:57

标签: 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'));

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

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)

3 个答案:

答案 0 :(得分:5)

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

Highcharts.chart('container', {
  chart: {
    events: {
      load: function() {
        staggerDataLabels(this.series);
      },
      redraw: function() {
        staggerDataLabels(this.series);
      }
    },
  },
  ...
});

function staggerDataLabels(series) {
  ...

答案 1 :(得分:1)

您想使用componentWillMount,因为它在组件的第一次渲染之前运行 - 将其与componentDidMount

的描述进行比较

var PLAYERS = [
  { name: "xyz", score: 123 },
  { name: 'abc', score: 111 },
  { name: 'def', score: 222 }
];

const Header = ({players}) =>
  <ul>{players.map(({name,score}) =>
    <li><span>{name}</span><span>{score}</span></li>)}</ul>

// App component
class App extends React.Component {

  // get rid of constructor if you're not doing anything with it
  // constructor() { ... }

  // use componentWillMount instead of componentDidMount
  componentWillMount() {
    this.setState({
      players: this.props.initialPlayers
    })
  }

  // don't wrap everything in a div if it's not necessary
  render() {    
    return <Header players={this.state.players} />
  }
}

// Render component
ReactDOM.render(<App initialPlayers={ PLAYERS }/>, 
document.getElementById('root'));
span {
  display: inline-block;
  font-weight: bold;
  margin-right: 1em;
}

span ~ span {
  font-weight: normal;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

答案 2 :(得分:0)

首先你需要初始化你的state,否则你会得到错误更新它的值,然后你必须使用setState方法来改变它(这是更新{{1}的推荐方法在反应中)

state