redux 无法从本地存储获取项目

ni65a41a  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(122)

无法从本地存储获取项目并显示它在store.js中,从本地存储获取shippingAddress,但未在表单中显示它我在shippingAddressSlice.js中设置shippingAddress,它工作正常,但当我尝试从本地存储获取它时,它无法正常工作

**编辑:**我在重新加载页面后获取数据,但我想在不重新加载页面的情况下获取数据
存储.js

import { configureStore } from '@reduxjs/toolkit';
import productListReducer from './features/productListFeature/productListSlice';
import productDetailsReducer from './features/productListFeature/productDetailSlice';
import CartReducer from './features/addToCart/cartSlice';
import userLoginReducer from './features/UserFeature/loginUserSlice';
import userRegisterReducer from './features/UserFeature/registerUserSlice';
import userDetailsReducer from './features/UserFeature/userDetailsSlice';
import userUpdateProfileReducer from './features/UserFeature/updateProfileSlice';
import ShippingAddressReducer from './features/shippingAddressSlice';

// yahan hum local storage sy data ly rahy hein jo cartSlice mein store kea tha ... JSON.parse is leye run kea hy kun k stringify kea tha data cartSlice mein
const cartItemsFromStorage = localStorage.getItem('cartItems')
  ? JSON.parse(localStorage.getItem('cartItems'))
  : [];

const userInfoFromStorage = localStorage.getItem('userInfo')
  ? JSON.parse(localStorage.getItem('userInfo'))
  : null; //agr user info ni available to null return kar do
const shippingAddressFromStorage = localStorage.getItem('shippingAddress')
  ? JSON.parse(localStorage.getItem('shippingAddress'))
  : {};
const initialState = {
  cart: {
    cartItems: cartItemsFromStorage,
    shippingAddress: shippingAddressFromStorage,
  },
  userLogin: {
    userInfo: userInfoFromStorage,
  },
};

const store = configureStore({
  reducer: {
    productList: productListReducer,
    productDetails: productDetailsReducer,
    cart: CartReducer,
    userLogin: userLoginReducer,
    userRegister: userRegisterReducer,
    userDetails: userDetailsReducer,
    userUpdateProfile: userUpdateProfileReducer,
    shippingAddress: ShippingAddressReducer,
  },
  preloadedState: initialState, //for local storage
});
export default store;

传送地址切片.js

import { createSlice } from '@reduxjs/toolkit';

const initialState = {};
const shippingAddressSlice = createSlice({
  name: 'ShippingAddress',
  initialState,
  reducers: {
    saveShippingAddress: (state, action) => {
      console.log(action.payload);
      localStorage.setItem('shippingAddress', JSON.stringify(action.payload));
      return {
        ...state,
        shippingAddress: action.payload,
      };
    },
  },
});
export const { saveShippingAddress, closeModal } = shippingAddressSlice.actions;
export default shippingAddressSlice.reducer;

传送屏幕.js

import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Button } from 'react-bootstrap';
import { useDispatch, useSelector } from 'react-redux';
import FormContainer from '../components/FormContainer';
import { saveShippingAddress } from '../features/shippingAddressSlice';
const ShippingScreen = () => {
  const cart = useSelector((store) => store.cart);
  const { shippingAddress } = cart;
  console.log(shippingAddress);
  const navigate = useNavigate();
  const dispatch = useDispatch();
  //agr localStorage mein ye hein to initial state set hojayegi
  const [address, setAddress] = useState(shippingAddress.address);
  const [city, setCity] = useState(shippingAddress.city);
  const [postalCode, setPostalCode] = useState(shippingAddress.country);
  const [country, setCountry] = useState(shippingAddress.country);
  const submitHandler = (e) => {
    e.preventDefault();
    dispatch(saveShippingAddress({ address, city, postalCode, country }));
    navigate('/payment');
  };
  return (
    <FormContainer>
      <h1>Shipping</h1>
      <Form onSubmit={submitHandler}>
        <Form.Group controlId='address'>
          <Form.Label>Address</Form.Label>
          <Form.Control
            type='address'
            placeholder='Enter Address'
            //uncontrolled to controlled mein change honay wala error khatam karny k leye ye kea
            value={address ? address : ''}
            required
            onChange={(e) => setAddress(e.target.value)}
          ></Form.Control>
        </Form.Group>

        <Form.Group controlId='city'>
          <Form.Label>City</Form.Label>
          <Form.Control
            type='city'
            placeholder='Enter City'
            value={city ? city : ''}
            required
            onChange={(e) => setCity(e.target.value)}
          ></Form.Control>
        </Form.Group>

        <Form.Group controlId='postalCode'>
          <Form.Label>postalcode</Form.Label>
          <Form.Control
            type='text'
            placeholder='Enter postalcode'
            value={postalCode ? postalCode : ''}
            required
            onChange={(e) => setPostalCode(e.target.value)}
          ></Form.Control>
        </Form.Group>
        <Form.Group controlId='country'>
          <Form.Label>Country</Form.Label>
          <Form.Control
            type='text'
            placeholder='Enter Country name'
            value={country ? country : ''}
            required
            onChange={(e) => setCountry(e.target.value)}
          ></Form.Control>
        </Form.Group>
        <Button variant='primary' type='submit'>
          Continue
        </Button>
      </Form>
    </FormContainer>
  );
};
export default ShippingScreen;
6ljaweal

6ljaweal1#

我认为这个问题是关于第一次页面加载失败检索数据与useSelector挂钩。
我认为你需要改变你的代码在shippingScreen.js与一些格式的代码和添加useEffect的获取数据之前,加载页面。
因此,在shippingScreen.js中,您应该使用以下代码更改代码:

import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Button } from 'react-bootstrap';
import { useDispatch, useSelector } from 'react-redux';
import FormContainer from '../components/FormContainer';
import { saveShippingAddress } from '../features/shippingAddressSlice';

import {store} from './store' // this will give you access to redux store

const ShippingScreen = () => {
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [shippingAddress, setShippingAddress] = useState({});
    useEffect(() => {

        const {shippingAddress} = store.getState().cart;
        setShippingAddress(shippingAddress);

    }, [])
    console.log(shippingAddress);
    //agr localStorage mein ye hein to initial state set hojayegi
    const [address, setAddress] = useState(shippingAddress.address);
    const [city, setCity] = useState(shippingAddress.city);
    const [postalCode, setPostalCode] = useState(shippingAddress.country);
    const [country, setCountry] = useState(shippingAddress.country);
    const submitHandler = (e) => {
        e.preventDefault();
        dispatch(saveShippingAddress({ address, city, postalCode, country }));
        navigate('/payment');
    };
    return (
        <FormContainer>
            <h1>Shipping</h1>
            <Form onSubmit={submitHandler}>
                <Form.Group controlId='address'>
                    <Form.Label>Address</Form.Label>
                    <Form.Control
                        type='address'
                        placeholder='Enter Address'
                        //uncontrolled to controlled mein change honay wala error khatam karny k leye ye kea
                        value={address ? address : ''}
                        required
                        onChange={(e) => setAddress(e.target.value)}
                    ></Form.Control>
                </Form.Group>

                <Form.Group controlId='city'>
                    <Form.Label>City</Form.Label>
                    <Form.Control
                        type='city'
                        placeholder='Enter City'
                        value={city ? city : ''}
                        required
                        onChange={(e) => setCity(e.target.value)}
                    ></Form.Control>
                </Form.Group>

                <Form.Group controlId='postalCode'>
                    <Form.Label>postalcode</Form.Label>
                    <Form.Control
                        type='text'
                        placeholder='Enter postalcode'
                        value={postalCode ? postalCode : ''}
                        required
                        onChange={(e) => setPostalCode(e.target.value)}
                    ></Form.Control>
                </Form.Group>
                <Form.Group controlId='country'>
                    <Form.Label>Country</Form.Label>
                    <Form.Control
                        type='text'
                        placeholder='Enter Country name'
                        value={country ? country : ''}
                        required
                        onChange={(e) => setCountry(e.target.value)}
                    ></Form.Control>
                </Form.Group>
                <Button variant='primary' type='submit'>
                    Continue
                </Button>
            </Form>
        </FormContainer>
    );
};
export default ShippingScreen;

它将在我的系统上完美地工作。我希望你也能够用这些小技巧解决这个问题。

相关问题