2016-11-20 48 views
0

我是redux的新手,試圖調用API並將返回的User對象數組傳遞給state.admin.usersRedux:調用API之後無法更新狀態

我的代碼:// 組件

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

控制檯輸出

狀態:{ 「管理員」:{}} bundle.js:2570:1

componentWillMount()bundle.js:295:8

OPTIONS 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:[{data除去} {數據中除去} {數據中除去}]

response.data看行˚F或者我。但上述代碼中的任何問題?爲什麼state.admin是空的?爲什麼componentWillMount()mapStateToProps之後叫?

歡迎任何評論。由於

回答

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鍵?

+0

似乎'派遣(類型:FETCH_ALL_USERS, 有效載荷:response.data });'失敗。 – BAE

+0

嘗試用錯誤情況重寫你的承諾代碼,作爲'then'而不是'catch'的第二個參數。 https://github.com/facebook/react/issues/7617#issuecomment-247710003 –