在我的应用程序组件中,我具有包含用户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中最后一个解析的用户。每个帖子都应该是相关的用户。
减速器和动作创建者
// 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]
之类的状态,为什么不能仅返回action.payload
来完成呢?我尝试过仅返回action.payload
来进行尝试,但是在我的用户组件中,每次发布时,它都会显示api中最后一个解析的用户。我对此感到困惑。
您正在使用mapStateToProps订阅商店,当商店发生更改时,该地图会重新提交。当您尝试通过User组件中的props进行渲染时,该应用程序会保留user的最后一个值,并重新渲染所有旧的User Components。如果您要忽略道具更新,请在组件本地生成结果。