Reactjs 当父过程发生更改时,如何重新渲染子组件(重新渲染)

Reactjs 当父过程发生更改时,如何重新渲染子组件(重新渲染),reactjs,redux,Reactjs,Redux,我对redux和react有点困惑 我有一个父组件(SingleList),用于呈现子组件(NutrientsTable)。父级传递给子级productList一段状态,然后componentDidMount中的子级调用更新CurrentListList的操作,然后我在Childrender()中使用该操作来显示 我尝试将calculateNutrients声明为组件中的just helper方法,然后分配给变量,然后在render()中使用它。因此,它工作得很好,但我要把所有的应用程序动作都放

我对redux和react有点困惑

我有一个父组件(SingleList),用于呈现子组件(NutrientsTable)。父级传递给子级productList一段状态,然后componentDidMount中的子级调用更新CurrentListList的操作,然后我在Childrender()中使用该操作来显示

我尝试将calculateNutrients声明为组件中的just helper方法,然后分配给变量,然后在render()中使用它。因此,它工作得很好,但我要把所有的应用程序动作都放到Action Creator中,所以我需要用redux来完成

母公司薪酬单一名单

import { connect } from "react-redux";
import NutrientsTable from "../NutrientsTable";

class SingleList extends Component {

  render() {
    return (
      <div className="single-list">
        <NutrientsTable 
          productsList={this.props.list.productsList}
        />
      </div>
    );
  }
}

function mapStateToProps({ lists }, ownProps) {
  return {
    list: lists[ownProps.match.params.id]
  };
}

export default connect(
  mapStateToProps,
  {}
)(SingleList);
减速器仅返回操作。有效负载


第一次渲染时一切正常,但当我在父级中执行某些操作并更改productList的状态时,子级不会使用新的productList重新渲染。我知道这是因为组件只调用了一个。但我应该在哪里采取行动?我无法用任何生命周期方法解决它。有什么建议吗?

首先,如果您使用的是Redux,那么如果Redux存储(应用程序状态)中存在数据,则不必将数据从父级传递给子级。只需对子组件使用
connect
。当检测到Redux存储(应用程序状态)中的任何更改时,子组件应该更新

第二,当您希望更改发生时,必须
和操作分派给Redux,告诉Redux调用api(或类似的东西)并更新其存储


要处理api调用,您应该使用Redux thunk或Redux saga。

如果您打算更新
NutrientsTable
永久使用
componentDidUpdate
以及
componentDidMount
,因为后者将仅在初始渲染中运行
componentDidUpdate
将在每次出现问题时运行。。。更新良好(状态或项目)。是的,我用componentDidUpdate做,但我把它放在父组件中,因为当我把它放在子组件中时,这里是一个有限循环。但我仍然不确定这是否是最好的方法,请记住,您必须对以前的道具和您要检查的新道具进行一些比较。如果它们不同,则运行该方法,否则不执行任何操作。这样可以避免无限循环。如果你仍然有一个无限循环,那就意味着你的代码有其他问题。如果您仍然遇到问题,请使用codesandbox或stackblitz提供一个小样本
import { connect } from 'react-redux';
import { calculateNutrients } from '../actions';

class NutrientsTable extends Component {

    componentDidMount() {
        this.props.calculateNutrients(this.props.productsList);
    }

    render() { 
        const { calories, carbohydrates, proteins, fats } = this.props.nutrients;

        return (
            <div>{calories} {carbohydrates} {proteins} {fats}</div>
        )
    }
}

const mapStateToProps = ({currentListNutrients}) => {
    return { nutrients: currentListNutrients }
}

export default connect(mapStateToProps, { calculateNutrients })(NutrientsTable);
export function calculateNutrients(productsList) {
  let calories = 0,
    carbohydrates = 0,
    proteins = 0,
    fats = 0;
  _.map(productsList, product => {
    product.calories && (calories += product.calories * product.count);
    product.carbohydrates && (carbohydrates += product.carbohydrates * product.count);
    product.proteins && (proteins += product.proteins * product.count);
    product.fats && (fats += product.fats * product.count);
  });

  return {
    type: CALCULATE_NUTRIENTS,
    payload: {calories, carbohydrates, proteins, fats}
  }
}