【问题标题】:State store not getting updated properly in redux状态存储在 redux 中未正确更新
【发布时间】:2019-06-02 15:31:38
【问题描述】:

我是 Redux 的新手,正在尝试在我的 React 应用中使用 Redux。

这是我的减速器。

车顶减速器 -

import {combineReducers} from 'redux';
import dataListReducer from './dataList';

export default combineReducers({
    dataListReducer
})

和dataList reducer-

const INITITAL_STATE={gridData:[]}

const dataListReducer=(state=INITITAL_STATE,action)=>{    
switch(action.type){
    default: return {...state}
}
return state;
}

export default dataListReducer;

这是动作创建者类 -

export const dataLoaded=(data)=>{
    return {
        type:'full_data',
         payload:{gridData:data}
    }
}

现在,我正在从下面的组件中对网络进行 Fetch 调用,当调用返回时,我想用最新数据更新应用程序状态 -

 componentDidMount()
{
  FetchService(this.state.url)
    .then((res)=> res.json())
    .then(  (result)=>this.updateState(result)                                   
         ).catch(function(error){console.log(error)});
}


updateState(result)
{
  this.props.dataLoaded(result);  
}

组件正在按规定调用连接 -

const mapStateToProps=(state)=>{  
  console.log(state);
return state;
}

export default connect(mapStateToProps,{dataLoaded})(Main) 

为什么console.log不打印最新数据?

我在这里错过了什么?

如果我可以进一步澄清,请告诉我。

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    您在 reducer 中所做的是返回它已经拥有的相同状态。所以它是一个 void reducer - 就像不采取任何行动一样。您需要做的是,当从 reducer 返回时,要真正考虑在 action 的有效负载中传递的内容。

    case "full_data": return { ...state, action.payload }

    或者我什至建议明确指定属性,以便进一步扩展并且不会覆盖任何同级

    case "full_data": return { ...state, ...gridData: action.payload.gridData }

    【讨论】:

    • 有道理。但是为什么这一行显示错误(Parsing error: Unexpected token, expected ",") return { ...state, action.payload }
    • 在示例中,我使用了spread 运算符,这是 ES6 的一个特性。如果您使用的是较旧的 JS 版本,则可以使用 Object.assign
    【解决方案2】:

    朋友,你还没有在你的 reducer 中定义任何东西来处理发送给它的操作。

    为此,您需要在减速器中设置一些案例,如下所示:

    const dataListReducer=(state=INITITAL_STATE,action)=>{    
        switch(action.type){
           case "full_data":
              return {...state, myData}
           default: 
              return state
    }
    

    这样你的减速器会在一个动作被分派给它时更新。

    【讨论】:

    • 我在将状态复制到新对象并返回它的开关中有一个缺陷。它应该工作正常吗?
    • 它可以工作,但它设置的状态与以前相同——没有更新。您应该改为在状态中设置有效负载的日期,以便您可以看到实际的 UI 更新。
    【解决方案3】:

    这应该适合你。

    const INITITAL_STATE={gridData:[]}
    
    const dataListReducer=(state=INITITAL_STATE,action)=>{    
      switch(action.type){
          case: 'full_data':
            return { ...state, gridData: action.payload.gridData }
          default: return {...state}
      }
    }
    
    export default dataListReducer;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2021-12-06
      • 2018-06-29
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 2019-05-15
      相关资源
      最近更新 更多