簡體   English   中英

獲取數據但狀態未更新

[英]data is fetched but the state is not updated

我從端點獲取數據。 但是州沒有更新。 它總是未定義的。

由於某種原因,this.props.users是未定義的。 難道我做錯了什么?

在componentDidMount()之后,我觸發了向端點發送請求的動作fetchUsers。 數據已成功獲取,但最后狀態未更新。

這是我的Layout組件


class Layout extends Component {
    render() {
        return (
            <div className="container">
                {
                    this.props.users.map((user, key) => {
                        return <a className="list-group-item list-group-item-action active">User #{user.id}</a>
                    })
                }
            </div>
        )
    }
}

const mapStateToProps = state => {
    return {
        channels: state.users.data,
    }
}

const mapDispatchToProps = dispatch => {
    return {
        fetchUsers: () =>
            dispatch(user.fetchUsers()),
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Layout);

這個動作文件

export const fetchUsers = () => {

    return (dispatch, getState) => {
        let headers = { "Content-Type": "application/json" };
        return fetch("http://127.0.0.1:3030/api/users/", { headers, })
            .then(res => {
                if (res.status < 500) {
                    return res.json().then(data => {
                        return { status: res.status, data };
                    })
                } else {
                    console.log("Server Error!");
                    throw res;
                }
            })
            .then(res => {
                if (res.status === 200) {
                    dispatch({ type: 'USERS_FETCHED', data: res.data });
                    return res.data;
                }
            })

    }
}

這是減速器

const initialState = {
    users: []
};

export default function channels(state = initialState, action) {
    switch (action.type) {
        case 'USERS_FETCHED':
            return { ...state, users: action.data };
        default:
            return state;
    }
}

我認為錯誤來自於您在mapDispatchToProps調度調度mapDispatchToProps 由於您直接導出函數fetchUsers ,因此不應該調用user.fetchUsers

const mapDispatchToProps = dispatch => {
    return {
        fetchUsers: () =>
            dispatch(fetchUsers()),
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM