我是Web开发的新手,正在尝试学习react和redux。
我正在关注本教程 https://www.youtube.com/playlist?list=PLC3y8-rFHvwheJHvseC3I0HuYI2f46oAK
在尝试扩展所学内容时, 我正在尝试列出所有用户(可点击), 一旦单击,将显示(展开/折叠)用户的所有帖子(再次单击), 点击帖子后,将显示(展开/折叠)该帖子的所有评论
要使用的API:
用户:https://jsonplaceholder.typicode.com/users
帖子:https://jsonplaceholder.typicode.com/posts?userId= {user.id}
评论:https://jsonplaceholder.typicode.com/comments?postId= {post.id}
我在获取用户数组时添加了属性collapse
,用于展开/折叠监控
我的问题是:
下面是我的UserContainer.js
import React, { useEffect } from "react";
import { connect } from "react-redux";
import { fetchUsers } from "../redux";
function UsersContainer({ userData, fetchUsers }) {
useEffect(() => {
fetchUsers();
}, []);
const handleClick = event => {
//console.log(userData.users)
const indx = userData.users.findIndex(obj => obj.id == event.target.value);
//console.log(indx)
userData.users[indx].collapse = !userData.users[indx].collapse;
console.log(userData.users[indx].collapse + " " + indx);
};
return userData.loading ? (
<h2>loading</h2>
) : userData.error ? (
<h2>{userData.error}</h2>
) : (
<div>
<h2>User List</h2>
<div className="list-group">
{userData.users.map(user => (
<div>
<button
type="button"
className="list-group-item list-group-item-action"
key={user.id}
onClick={handleClick}
value={user.id}
>
{user.name}
</button>
{/* for update to change SampleContainer component to POST component */}
{user.collapse && <SampleContainer id={user.id} name={user.name} />}
</div>
))}
</div>
</div>
);
}
const mapStateToProps = state => {
return {
userData: state.user
};
};
const mapDispatchToProps = dispatch => {
return {
fetchUsers: () => dispatch(fetchUsers())
};
};
const SampleContainer = props => {
return (
<div>
{/* trying to pass the id/name in prep for POST component*/}
display Posts of - {props.name} ({props.id}){" "}
</div>
);
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(UsersContainer);
这是codeandbox链接: https://codesandbox.io/s/react-redux-testing-mi6ms
答案 0 :(得分:1)
您正在直接更新不可更改的userData
道具,即它们无法更改且不更新UI。您将需要通过调度新操作来更新您的redux存储,在这种情况下,该存储将为UPDATE_USER_STATUS
。
这是一个codesandbox,上面有一个有效的示例。