【问题标题】:Redux: cannot update state after calling APIsRedux:调用 API 后无法更新状态
【发布时间】:2016-11-20 19:51:55
【问题描述】:

我是 redux 的新手,尝试调用 API 并将返回的用户对象数组传递给 state.admin.users

我的代码: //组件

class MyComponent extends Component {
  componentWillMount() {
    console.log( 'componentWillMount()' );
    this.props.fetchAllUsers();
  }

  render() {
    return (
      <div>
        <ul>
        {
           this.props.users.map( function(user) {
              return <div>user.email</div> })
        }
        </ul>
      </div>
    );
  }
}

function mapStateToProps(state) {
    console.log( 'state:' + JSON.stringify(state) );
    return  {
        users: state.admin.users
    }
}

export default connect(mapStateToProps, {fetchAllUsers})(myComponent);

// 减速器

const INITIAL_STATE = { users:[] };

export default function (state = INITIAL_STATE, action) {
  return { ...state, users:action.payload }; // Any problem here?
}

// 动作

export function fetchAllUsers() {
  return function(dispatch) {
    axios.get(`${API_URL}/users`)
    .then(response => {
      console.log( 'response.data:' +JSON.stringify(response.data) );
      dispatch({
        type: FETCH_ALL_USERS,
        payload: response.data // Any problems here?
      });
    })
    .catch(response => dispatch(errorHandler(response.data.error)))
  }
}

控制台输出

state:{"admin":{}} bundle.js:2570:1

componentWillMount() bundle.js:295:8

选项 XHR http://myip:3001/api/users [HTTP/1.1 200 OK 2ms]

GET XHR http://myip:3001/api/users [HTTP/1.1 304 未修改 4ms]

response.data:[{数据已删除}{数据已删除}{数据已删除}]

response.data 对我来说看起来不错。但是上面的代码有什么问题吗?为什么 state.admin 是空的?为什么componentWillMount()mapStateToProps 之后调用?

欢迎任何 cmets。谢谢

【问题讨论】:

    标签: javascript redux react-redux redux-thunk


    【解决方案1】:

    你的减速器应该是这样的:

    export default function (state = INITIAL_STATE, action) {
      switch (action.type) {
        case FETCH_ALL_USERS:
          return Object.assign({}, state, {
            users: action.payload
          });
      }
      return state;
    }
    

    此外,您的 sn-ps 不会显示您是如何定义根减速器的。它是否有一个指向这个减速器的admin 键?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2018-07-21
    • 2020-04-14
    • 2023-03-19
    • 1970-01-01
    • 2019-12-04
    • 2021-04-22
    相关资源
    最近更新 更多