2016-11-20 5 views
0

저는 redux에 익숙하며 API를 호출하고 반환 된 User 객체 배열을 state.admin.users으로 전달하려고합니다.Redux : 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))) 
    } 
} 

콘솔 출력

,536 91,363,210

상태 { "관리자"는 {}} bundle.js : 2,570 : 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 제거} {데이터가 제거} {데이터 OK F 보일 response.data

]} 삭제 아니면 나. 위의 코드에있는 문제는 무엇입니까? 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

'dispatch ({ 유형 : FETCH_ALL_USERS, 페이로드 : response.data });'가 실패했습니다. – BAE

+0

'catch' 대신'then'에 대한 두 번째 인수로 오류 코드를 사용하여 약속 코드를 다시 작성하십시오. https://github.com/facebook/react/issues/7617#issuecomment-247710003 –