【问题标题】:why I am getting store is undefined error?为什么我得到 store is undefined 错误?
【发布时间】: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


【解决方案1】:

只需导入configureStore: import { configureStore } from '@reduxjs/toolkit'

【讨论】:

  • 已导入。问题还是一样。
  • 你在哪里为你的组件树提供 redux 提供者?添加必要的信息
【解决方案2】:

很遗憾,我将商店添加到了错误的位置,这就是我收到错误消息的原因。问题已经解决了。

【讨论】:

    猜你喜欢
    • 2019-01-15
    • 1970-01-01
    • 2018-07-19
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 2011-10-20
    • 2020-12-16
    相关资源
    最近更新 更多