最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set state from props that is passed to the component in react? - Stack Overflow

programmeradmin6浏览0评论

I have this simple ponent, initialPlayers props is passed to App ponent.

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

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

// App ponent
class App extends React.Component {

 constructor() {
   super();
 }

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

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

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

Have this error in console, and not able to pass value to Header ponent as {this.state.players}. 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)

I have this simple ponent, initialPlayers props is passed to App ponent.

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

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

// App ponent
class App extends React.Component {

 constructor() {
   super();
 }

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

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

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

Have this error in console, and not able to pass value to Header ponent as {this.state.players}. 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)
Share Improve this question asked Apr 25, 2017 at 21:08 Anoop MundathanAnoop Mundathan 2453 gold badges5 silver badges12 bronze badges 1
  • Possible duplicate of React ponent initialize state from props – Jalal Commented Dec 11, 2017 at 18:52
Add a ment  | 

3 Answers 3

Reset to default 8

Move the setting players line into your constructor():

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

You want to use ponentWillMount because it runs before the ponent's first render – pare that to the description of ponentDidMount

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 ponent
class App extends React.Component {

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

  // use ponentWillMount instead of ponentDidMount
  ponentWillMount() {
    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 ponent
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./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./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 remended way to update state in react)

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: []
    };
  }
  ponentDidMount() {
    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')
);
发布评论

评论列表(0)

  1. 暂无评论