【问题标题】:Redux store updating, but React views is notRedux 存储更新,但 React 视图不是
【发布时间】:2019-03-11 18:07:07
【问题描述】:

嗨,当我在控制台记录我的组件道具(从 redux 传递下来)时,我得到的初始状态为空。但是使用反应检查器我得到了 axios 请求的结果。我尝试阅读几十个类似的问题,但无法解决我的问题。

操作

import { searchService } from  '../api/searchService';    

export const actions = {
 FETCH_USERS: 'FETCH_USERS',
}

export const searchUsers = () => dispatch => {
  searchService.get('/search')
    .then((result) => {
      dispatch({
        type: actions.FETCH_USERS,
        payload: result
      })
    })
}

减速器

import { actions } from '../actions';

export default (state = null, action) => {
  switch(action.type) {
    case actions.FETCH_USERS:
      return action.payload;
    default:
      return state;
  }
}

搜索组件

function mapStateToProps ({search}) {
  return {search};
}

const mapDispatchToProps = dispatch => ({
  searchUsers: () => dispatch(searchUsers())
});


export default connect(mapStateToProps, mapDispatchToProps)(withAuth()(Search));

【问题讨论】:

    标签: reactjs redux axios redux-thunk


    【解决方案1】:

    你的问题出在减速器上 首先你应该做一个初始状态,然后你需要编辑这个状态才能让 redux 感受到变化并更新

    检查下面的代码,让我知道它是否适合您。

    import { actions } from '../actions';
    
    const INITIAL_STATE= {search: ""};
    
    export default (state = INITIAL_STATE, action) => {
      switch(action.type) {
        case actions.FETCH_USERS:
          return {...state, search: action.payload};
        default:
          return state;
      }
    }
    

    【讨论】:

    • 嘿,威利,我使用了你的代码,现在我的控制台日志所做的只是:搜索:“”。但是我的 React 调试器仍然有正确的状态(获取数据).....
    猜你喜欢
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 2018-10-15
    • 2021-02-24
    相关资源
    最近更新 更多