简体   繁体   English

如何从 store/react redux 获取数据

[英]How to get data from store / react redux

 const initialState = {
   id: null,
   username: "",
   email: "",
   avatar_url: "",
   userLoad_error: false,
   error_message: "",
 };
 Slice
 const user = createSlice({
   name: "user",
   initialState,
   reducers: {
     UserLoadData(state, action) {
       state.id = action.payload.id;
       state.username = action.payload.username;
       state.email = action.payload.email;
       state.avatar_url = action.payload.avatar_url;
     },
     UserFaildLoadData(state, action) {
       state.userLoad_error = action.payload.error;
       state.error_message = action.payload.error_message;
     },
   },
 });
 Api
 const { UserLoadData, UserFaildLoadData } = user.actions;
 export function UserLoad() {
   return async (dispatch) => {
     try {
       const response = await API.get("/user");
       const data = response.data;
 
       const id = data.data.id;
       const username = data.data.username;
       const email = data.data.email;
       const avatar_url = data.data.avatar.url;
 
       dispatch(
         UserLoadData({
           id: id,
           username: username,
           email: email,
           avatar_url: avatar_url
         })
       );
     } catch (e) {
       const error = e.response;
       let error_message = null;
 
       if (error) {
         if (error.status === 401) error_message = "Wrong data!";
       } else error_message = "No connection to the server!";
       dispatch(
         UserFaildLoadData({
           login_error: true,
           error_message,
         })
       );
     }
   };
 }
 
 FrontEnd
     const dispatch = useDispatch();
     useEffect(() => {
         dispatch(UserLoad())
     }, [])

React-Redux-Store. React-Redux-Store。 How to use data from store, im beginner in react and redux, so i even dont understand how to get data after dispatch and where its store.如何使用来自 store 的数据,我是 react 和 redux 的初学者,所以我什至不明白如何在调度后获取数据以及它的存储位置。

// //

You would use the useSelector hook for that.您将为此使用useSelector挂钩。 But honestly, this looks like you are taking the tenths step before the first step here, because figuring out how your components interact with Redux should come a long time before you write asynchronous data fetching logic.但老实说,这看起来你是在第一步之前迈出了第十步,因为在你编写异步数据获取逻辑之前,要花很长时间弄清楚你的组件如何与 Redux 交互。

I would highly recommend that you follow the official Redux tutorial from the beginning .我强烈建议您从头开始遵循官方的 Redux 教程

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

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