简体   繁体   English

获取数据但状态未更新

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

I'm fetching data from an endpoint. 我从端点获取数据。 But the state is not updated. 但是州没有更新。 it's always undefined. 它总是未定义的。

For some reason this.props.users is undefined. 由于某种原因,this.props.users是未定义的。 Am I doing something wrong? 难道我做错了什么?

After componentDidMount() I trigger the action fetchUsers that send a request to the endpoint. 在componentDidMount()之后,我触发了向端点发送请求的动作fetchUsers。 The data is fetched successfully but at the end the state is not updated. 数据已成功获取,但最后状态未更新。

This is my Layout component 这是我的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);

This the action file 这个动作文件

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

    }
}

And this is the reducer 这是减速器

const initialState = {
    users: []
};

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

I think the error comes from your call to the dispatcher in the mapDispatchToProps . 我认为错误来自于您在mapDispatchToProps调度调度mapDispatchToProps Since you are exporting directly the function fetchUsers , you should not be calling user.fetchUsers . 由于您直接导出函数fetchUsers ,因此不应该调用user.fetchUsers

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM