【问题标题】:React Redux infinite loopReact Redux 无限循环
【发布时间】:2016-07-13 18:52:20
【问题描述】:

当用户更新输入栏时,我打算执行对我的 rest api 的提取。我遇到的问题是 componentDidUpdate 方法调用将 json 分派到 reducer 的操作创建者,进而更新状态并再次调用 componentDidUpdate。有什么想法或最佳实践来结束无休止的循环吗?谢谢!

动作创建者:

export const fetchFoods = (dispatch, searchText) => {
  return fetch(`/nutrition/${searchText}`)
    .then(res => res.json())
    .then(json => dispatch({type: 'RECEIVE_FOODS', json}))
}

减速机:

const foods = (state = [], action) => {
  switch (action.type) {
    case 'RECEIVE_FOODS':
      return action.json
    default:
      return state
  }
}

反应容器:

const FoodList = React.createClass({
  componentDidUpdate: function() {
    fetchFoods(this.props.dispatch, this.props.searchText)
  },
  componentWillMount: function() {
    fetchFoods(this.props.dispatch, this.props.searchText)
  },
  render: function() {
    ...
  }
})

export default connect(
  (state) => {
    return {searchText: state.searchText, foods: state.foods}
  }
)(FoodList)

【问题讨论】:

  • 您在更新后立即更新,这会强制更新。
  • 您可能希望使用mapDispatchToPropsconnect 在输入更改时触发操作。还解释了here

标签: reactjs redux


【解决方案1】:

您应该从componentDidUpdate 中删除fetchFoods 函数。在更新时调用该函数将导致您描述的无限循环。

一旦组件第一次挂载并检索到原始数据集,您应该只在明确需要时调用该操作。如果用户改变它,另一个函数改变它,等等。

【讨论】:

    【解决方案2】:

    将 onChange() 处理程序附加到您的输入(或您想要触发更新的任何内容),以便每当输入更改时,它都会调用一个显式调度该操作的函数。

    https://jsfiddle.net/julianljk/69z2wepo/49105/

    功能:

    handleChange: function (e) {
        var myInput = e.target.value;
        this.setState({
            value: myInput
        });
        fetchFoods(this.props.dispatch, myInput) //sends it to the store, 
    },        
    

    渲染:

    render: function (){
        return( 
            <div>
                <input type="text" value={this.state.value} onChange={this.handleChange}/>
            </div>
    )}    
    

    将动作调度放入生命周期方法中通常会导致这种行为。

    【讨论】:

      猜你喜欢
      • 2017-04-19
      • 2021-01-02
      • 2019-02-09
      • 2018-03-24
      • 1970-01-01
      • 2020-03-12
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多