道具更新后没有正确调用render()方法

时间:2016-09-23 00:10:22

标签: reactjs redux react-jsx

我正在做一个非常简单的react + redux应用程序,其中我有一个名为goals的reducer和一个名为GoalsContainer的容器。

从App容器中调用操作目标,从本地db(indexedDB)

加载初始目标
dispatch(loadGoals(currentDate));

这会从目标操作中调用loadGoals:

export function loadGoals(currentDate = new Date()){
  return dispatch => {
    var goals = getGoalsFromDB(normalizeDate(currentDate)); // with this I get an array from the db
    dispatch(setLoadGoals(goals));
  }
}

function setLoadGoals(goals) {
  return {
    type: types.LOAD_GOALS,
    goals
  };
}

然后在我的减速机中,我就是这样:

export default function goals(state = [], action) {
  switch(action.type) {
    case types.LOAD_GOALS:
      return action.goals; // here I set the state of the goal reducer with the array passed via action
    default:
      console.log('Im here');
      return state;
  }
}

这是我的GoalsContainer(阅读代码中的注释):

class GoalsContainer extends React.Component {
  render() {
    if (this.props.goals != undefined) {
      console.log('ok called the render'); // in chrome console shows it
      console.log(this.props.goals); // in chrome console shows correctly the goals loaded
      console.log(this.props.goals.length); // it say 2
      if (this.props.goals.length > 0) { // here fails...
        console.log('good');
        console.log(this.props.goals);
        var goalsView = <div>There are goals</div>
      }
      else {
        console.log('why go here?'); // go here
        console.log(this.props.goals);
        var goalsView = <div>No goals</div>
      }
    } else {
      var goalsView = <div>Undefined</div>
    }
    return (
      <div id="goals-main">
        {goalsView}
      </div>
    );
  }
}

GoalsContainer.propTypes = propTypes;

function mapStateToProps(state) {
  const { goals, environment } = state;
  const { currentDate } = environment;

  return {
    goals,
    currentDate
  }
}

export default connect(mapStateToProps)(GoalsContainer);

问题在于,当它执行if检查时,它会失败(如果有0个目标),但在chrome控制台中正确显示目标数组... 然后,如果我强制使用render()一些解决方法,那么一切都正常。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您没有提及是否使用https://github.com/gaearon/redux-thunk。要使用reducer返回功能,你一定要安装它。

答案 1 :(得分:0)

很难从随机要点中跟踪代码的所有部分。如果您将GoalsContainer更改为

,会发生什么情况
class GoalsContainer extends React.Component {
  render() {
    console.log(this.props.goals);
    return (
      <div id="goals-main">
        {(this.props.goals.length >= 1)?<div>There are goals</div>:<div>Nope!</div>}
      </div>
    );
  }
}

什么记录到控制台?