updating objects with setState in React

前端 未结 1 1630
太阳男子
太阳男子 2021-02-19 06:07

How can I pass multiple states to setState? Here\'s an example:

getInitialState: function() {
  return {
    list: [],
    newFilm: {},
    searchWo         


        
1条回答
  •  北荒
    北荒 (楼主)
    2021-02-19 06:20

    There is no syntax problem with the way you are setting state, but there could be a problem with the way you are initialising you state. You have initialized newFilm as an object state but when you set its state you are giving a string. So suppose you try to render it like {this.state.newFilm} it will throw you an error

    Objects are not valid as a React child (found: object with keys {}).

    as you can see in the snippet below, since the first time the component is rendered it sees an object where later its only a string.

    To fix this try initializing you state newFilm as '' or take prevention when you try to render i.e. check where it contains some data and then only render.

    Also I don't see someData defined in your componentDidMount function. You need to define it before you can use it.

    var App = React.createClass({
      getInitialState: function() {
      return {
        list: [],
        newFilm: {},
        searchWord: '',
        searchDetails: {}
      }
    },
    
    componentDidMount: function() {
      var someData = {'name': 'abc'};
      this.setState({
        searchDetails:someData,
        newFilm: 'I am first text',
      })
    },
    render: function() {
      console.log(this.state.newFilm);
      return (
        
    {this.state.newFilm}
    ) } }) ReactDOM.render(, document.getElementById('app'));
    
    
    

    0 讨论(0)
提交回复
热议问题