Redux:调用API后无法更新状态

时间:2016-11-20 19:51:55

标签: javascript redux react-redux redux-thunk

我是redux的新手,尝试调用API并将返回的User对象数组传递给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);

// reducer

const INITIAL_STATE = { users:[] };

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

// actions

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)))
  }
}

控制台输出

  

陈述:{&#34; admin&#34;:{}} bundle.js:2570:1

     

componentWillMount()bundle.js:295:8

     

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

     

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

     

response.data:[{data removed} {data removed} {data removed}]

response.data对我来说很好看。但上述代码中的任何问题?为什么state.admin是空的?为什么componentWillMount()mapStateToProps之后调用?

欢迎任何评论。感谢

1 个答案:

答案 0 :(得分:0)

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

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

此外,您的代码段不会显示您如何定义根减速器。它是否有admin键指向此缩减器?