【发布时间】:2021-08-06 17:37:01
【问题描述】:
希望你做得很好。在这里,我试图将获取的数据存储到我的 redux 存储中,然后想在我的组件上使用这些数据,但突然我收到一个错误,。 我的商店的代码是,
import { configureStore } from "@reduxjs/toolkit";
import userReducer from "../features/userSlice";
export default configureStore({
reducer: {
user: userReducer,
},
});
我的 userSlice 的代码是,
const userSlice = createSlice({
name: "user",
initialState: {
posts: [],
},
reducers: {
setPosts: (state, action) => {
state.posts = action.payload;
},
},
});
export const { setPosts } = userSlice.actions;
export const selectPosts = (state) => state.user.posts;
export default userSlice.reducer;
我试图访问存储数据的组件是,
import { useSelector, useDispatch } from "react-redux";
import axios from "axios";
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import img from "../assets/index.jpeg";
import { Link } from "react-router-dom";
import { setPosts, selectPosts } from "../redux/features/userSlice";
function Posts() {
//const [state, setState] = useState([]);
const dispatch = useDispatch();
const posts = useSelector(selectPosts);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then((response) => {
//setState(response);
console.log("fetched");
dispatch(setPosts(response));
})
.catch((e) => console.log(e));
}, []);
return (
<div className="Posts">
<div>
<Container>
<Row>
{console.log(posts)}
{/* {!posts &&
posts.data.map((post) => (
<Col
xs={3}
style={{
margin: "15px",
cursor: "pointer",
border: "1px black solid",
}}
>
<div className="post__data">
<img alt="image" src={img} />
{post.title}
<Link to={"/post/" + post.id}>See more</Link>
</div>
</Col>
))} */}
</Row>
</Container>
</div>
</div>
);
}
export default Posts;
如果我能找到这个奇怪问题的解决方案,我会很高兴。提前致谢。
【问题讨论】:
-
你为你的 react 应用提供了 store 吗?
-
是的。!但问题还是一样。
-
仅此信息不清楚是什么问题,尝试添加更多信息,例如完整的
index.js文件、完整的存储文件、完整的切片文件
标签: javascript reactjs redux react-redux react-hooks