简体   繁体   English

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

[英]How to set state from props that is passed to the component in react?

I have this simple component, initialPlayers props is passed to App component. 我有这个简单的组件, 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'));

Have this error in console, and not able to pass value to Header component as {this.state.players} . 在控制台中出现此错误,并且无法将值作为{this.state.players}传递给Header组件。 Any idea?. 任何的想法?。

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)

Move the setting players line into your constructor(): 将设置播放器行移动到构造函数()中:

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

You want to use componentWillMount because it runs before the component's first render – compare that to the description of componentDidMount 您想使用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> 

First you need to initialize your state otherwise you'll get error updating it's value, then you have to use setState method to change it (this is the recommended way to update state in react) 首先你需要初始化你的state否则你会得到错误更新它的值,然后你必须使用setState方法来改变它(这是更新state的推荐方法)

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

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

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      players: []
    };
  }
  componentDidMount() {
    this.setState({
      players: this.props.initialPlayers
    });
  }
  render() {
    return(
      <div>
        <ul>
          {this.renderPlayers()}
        </ul>
      </div>
    );
  }
  renderPlayers() {
    return this.state.players.map((player, index) =>
      <li key={index}>{`name: ${player.name} - score: ${player.score}`}</li>
    );
  }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM