繁体   English   中英

React 在使用带有 redux-thunk 的异步动作创建器时获取无效状态

[英]React getting Invalid state while using async action creator with redux-thunk

在我的应用程序组件中,我有包含用户 ID 的帖子列表,我想根据该用户 ID 显示用户名和详细信息,这是我的应用程序组件的 jsx:

应用组件 JSX:

render() {
    const posts = [...someListOfPosts];
    return posts.map((post) => {
        return (
            <div className="item" key={post.id}>
                <div className="content">
                    <User userId={post.userId} />
                </div>
            </div>
        );
    });
}

用户组件

import React from 'react';
import { connect } from 'react-redux';
import { fetchUser } from '../actions';

class UserHeader extends React.Component {

    componentDidMount() {
        this.props.fetchUser(this.props.userId); // getting correct userId
    }

    render() {
        const { user } = this.props;
        // Not displaying correct user i.e. showing the last resolved user for each post
        return (
            <div>
                {user && <div className="header">{user.name}</div>}
            </div>
        );
    }
}

const mapStateToProps = (state, props) => {
    return {
        user: state.user
    };
}

export default connect(mapStateToProps, { fetchUser })(UserHeader);

我得到了 userId 的正确道具,但对于每篇文章,它都会显示来自 api 的最后一个解析的用户。 它应该是每个帖子的相关用户。

Reducer 和 Action Creator

// action

export const fetchUser = (id) => {
    return async (dispatch) => {
        const response = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`);
        dispatch({
            type: 'FETCH_USER',
            payload: (response.status === 200 && response.data) ? response.data : null; // it returns single user not array of user
        });
    }
}

// reducer

export default (state = null, action) => {
    switch (action.type) {
        case 'FETCH_USER':
            return action.payload; // i know it can be fixed by defaulting state to empty array and returning like so [...state, action.payload] but why should i return complete state why not just a single user object here?
        default:
            return state;
    }
}

fetchUser 操作创建者返回用户的单个有效负载而不是数组,那么为什么需要返回像[...state, action.payload]这样的[...state, action.payload]为什么不能通过仅返回action.payload来完成? 我已经通过仅返回action.payload尝试,但在我的用户组件中,它每次都显示来自 api 的最后解析的用户。 我对此感到困惑。

您正在使用 mapStateToProps 订阅商店,它会在商店发生变化时重新呈现。 当您尝试通过 User 组件中的 props 进行渲染时,应用程序会保留 user 的最后一个值并重新渲染所有旧的 User 组件。 如果您想忽略 props 更新,则将结果本地化到组件中。

你可以试试这个:

import React from 'react';
import { connect } from 'react-redux';
import { fetchUser } from '../actions';

class UserHeader extends React.Component {
constructor(props){
super(props);
this.state={
userDetails:{}
}
}

    componentDidMount() {
fetch(https://jsonplaceholder.typicode.com/users/${this.props.userId})
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            userDetails: result.data
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: false
          });
        }
      )

    }

    render() {
        return (
            <div>
                {this.state.userDetails && <div className="header">{this.state.userDetails.name}</div>}
            </div>
        );
    }
}

const mapStateToProps = (state, props) => {
    return {

    };
}

export default connect(mapStateToProps, { fetchUser })(UserHeader);

暂无
暂无

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

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