【问题标题】:React not rendering on state change反应不呈现状态变化
【发布时间】:2017-02-24 10:23:52
【问题描述】:

代码如下:

class Twitch extends React.Component {
  constructor(props){
    super(props);
    this.state={
      channelList:null,
      streamError:false,
      channelError:false,

    }
    self=this;
    this.getChannels = this.getChannels.bind(this);
  }

  componentWillMount() {
    this.getChannels();
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.channelList !== nextState.channelList) {
      return true;
    }
    return false;
  }

  getChannels(){
    let channels=["ESL_SC2", "OgamingSC2", 
                  "cretetion", "freecodecamp", 
                  "storbeck", "habathcx", 
                  "RobotCaleb", "noobs2ninjas", 
                  "brunofin", "comster404"
                 ];

    let resultSet=[];
    channels.map(function(channel){
      axios.get('https://wind-bow.gomix.me/twitch-api/streams/'+channel)
      .then(function (response) {
         let resObj={};
         resObj=response.data;
         axios.get('https://wind-bow.gomix.me/twitch-api/channels/'+channel)
         .then(function (response) {
            resObj.channel=response.data;
            resultSet.push(resObj);

         })
         .catch(function (error) {
            console.log("channel error",error.response);
            this.setState({channelError:true});
         });

      })
      .catch(function (error) {
            console.log("stream error",error.response);
            this.setState({streamError:true});
      });
    })
    this.setState({channelList:resultSet});
  }

  render(){
    console.log('this.state',this.state);// ---------a
    const {channelList} =this.state;
    return(
      <div className="container"> 

        {channelList.length>0 &&
          <div>
           //render stuff here 

         </div>         
        }
      </div>
    );
  }
}


ReactDOM.render(
  <Twitch />,
  document.getElementById('app')
);

API 调用工作正常,我正在获取状态数据。然而,重新渲染没有发生。 console.log(a) 首先返回数组长度 0,扩展时返回适当的长度。

【问题讨论】:

  • 您是否在this.setState({channelList:resultSet}); 之前检查过resultSet 是否为空?
  • 我向它添加了数据。我在 .then() 上做了 setState 。即使那样它也不起作用
  • 那么在resultSet中肯定有数据,但是在setState之后调用的render中this.state是空的?
  • 起初它是空的。然后当它展开时有数据

标签: javascript reactjs axios react-dom


【解决方案1】:

我解决了。 原来shouldComponentUpdate 正在返回 false 并且不让重新渲染发生。 我删除了那个方法。现在它工作正常

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2019-03-27
    • 1970-01-01
    相关资源
    最近更新 更多