屏幕甚至不改变道具就重新渲染?

时间:2018-10-08 00:37:55

标签: javascript reactjs react-native redux state

我当前面临的问题是屏幕无法重新渲染以将新添加的值加载到数组。即使尝试使用componentWillReceiveProps并手动触发this.forceUpdate()也无济于事。屏幕仅在我重新启动应用程序时显示新值

this.props.addNewRecord({ 
    recordDetails: { ...this.props.recordDetails, type: this.state.type },
    records: this.props.records
  });

return (
  <View>
    {
      this.props.records.map((x, i) => {
        return (
          <View style={{ flexDirection: 'row' }}>
            <Text>{`${i}: `}</Text>
            <Text>{x.id}</Text>
          </View>
        );
      })
    }
  </View>
);

const mapStateToProps = ({ account, settings, main }) => {
  const year = moment().year();
  const month = moment().format('MMM');

  return {
    records: account.records[year][month].records,
  };
};

export default connect(mapStateToProps)(SummaryScreen);

account.records具有以下结构

{
  2018: {
    Jan: {
      records: [{...}, {...}]
    }
  }
}

下面是添加记录部分

const addNewRecord = ({ recordDetails, records }) => {
  const year = moment(recordDetails.date).year();
  const month = moment(recordDetails.date).format('MMM');

  const newRec = {
    id: uuidv4(),
    account_id: recordDetails.account_id,
    date: recordDetails.date,
    description: recordDetails.description,
    amount: recordDetails.result,
    type: recordDetails.type
  };

  update(year, month, newRec, records);

  return {
    type: ADD_NEW_RECORD,
    payload: records
  };
};

const update = (year, month, obj, target) => {
  [year, month].reduce((r, e, i, a) => {
    if (!a[i + 1] && r[e]) {
      r[e].records.push(obj);

      if (obj.type === 'expense') r[e].totalExpenses = parseFloat(r[e].totalExpenses) + parseFloat(obj.amount);
      if (obj.type === 'income') r[e].totalIncome = parseFloat(r[e].totalIncome) + parseFloat(obj.amount);
    }
    return r[e] = (r[e] || (a[i + 1] ? {} : {
      records: [obj],
      totalExpenses: obj.type === 'expense' ? parseFloat(obj.amount) : 0,
      totalIncome: obj.type === 'income' ? parseFloat(obj.amount) : 0,
      type: obj.type
    }));
  }, target);
};

和减速器如下:

switch (action.type) {
  case ADD_NEW_RECORD:
    return { ...state, records: action.payload };

1 个答案:

答案 0 :(得分:1)

this.props.addNewRecord({ 
  recordDetails: { ...this.props.recordDetails, type: this.state.type },
  records: _.cloneDeep(this.props.records)//this.props.records
});

问题是我将this.props.records传递给records,后来被突变,最终旧状态被突变为与新状态相同,这就是Redux无法发现差异的原因。

发现此漏洞的原因是@ Y.Gherbi。希望对遇到同样问题的人有帮助