首页 > 解决方案 > react redux依赖如何与redux一起工作

问题描述

我编写了一个代码来使用 JWT 管理用户配置文件,我使用 useState 来管理表单输入并使用 redux 来管理数据。输入未使用我们从 api/action 接收的数据进行更新

import React, { useEffect, useState } from 'react'
import {useDispatch, useSelector} from 'react-redux'
import {getUser , updateUser} from '../actions/userActions'
import '../css/profile.css'
import {listMyOrders} from '../actions/orderActions'
import { Link } from 'react-router-dom'

const Profile = ({history}) => {

    const dispatch = useDispatch();
    const [name , setName] = useState('');
    const [email , setEmail] = useState('');
    const [password , setPassword] = useState('');
    const [confirmPassword , setConfirmPassword] = useState('');

    const userLogin = useSelector((state) => state.userLogin);

    
    const userProfile = useSelector((state) => state.userProfile);
    const {userData , loading , error} = userProfile;

    const myOrders = useSelector(state => state.orderListMy);
    const {orders , loading:loadingOrders} = myOrders;

    useEffect(
        async () => {
            if (!userLogin.userData) {
                history.push('/login')
            } else {
                if (!userData || !userData.name) {
                    dispatch(getUser());
                    dispatch(listMyOrders());
                }
                if(!myOrders.order){
                    dispatch(listMyOrders());
                }
                else {
                    setName(userData.name);
                    setEmail(userData.email);
                }
            }
            }
        , [dispatch, history , userData , userLogin.userData]);

        const handleUpdate = () => {
            if(password == confirmPassword) {
                dispatch(updateUser( userData._id , loading , name , email , password));
            }
        }


    return (
        <section id="profile">
            <div className="inside">
                <div className="user-profile">
                <p className="title">User Profile</p>
                <div className="msg-container">
                </div>
                <div className="name-container">
                    <label className="name-label">Name</label>
                    <input type="name" onLoad={ (e) =>
                        setTimeout(console.log('hello') , 1000)
                    } onChange={(e) => setName(e.target.value)} value={name} placeholder="Your Name" htmlFor="name" />
                </div>
                <div className="email-container">
                    <label className="email-label">Email Address</label>
                    <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="email address" htmlFor="email" />
                </div>
                <div className="password-container">
                    <label className="password-label">Password</label>
                    <input type="password" placeholder="Password" htmlFor="password" />
                </div>
                <div className="password-container">
                    <label className="password-label">Confirm Password</label>
                    <input type="password" placeholder="Confirm Password" htmlFor="password" />
                </div>
                <button onClick={handleUpdate} className="submit">Update</button>
                </div>
                <div className="my-orders">
                <div className="title">My Orders</div>
                    <table>
                    <thead>
                        <tr>
                        <td>ID</td>
                        <td>DATE</td>
                        <td>TOTAL</td>
                        <td>PAID</td>
                        <td>DELIVERED</td>
                        <td />
                        </tr>
                    </thead>
                    <tbody>
                        {!loadingOrders && orders.map(order => (
                        <tr key={order._id}>
                        <td>{order._id}</td>
                        <td>{order.createdAt.substring(0, 10)}</td>
                        <td>{order.totalPrice}</td>
                        <td>{order.isPaid ? (
                      order.paidAt.substring(0, 10)
                    ) : (
                      <i className='fas fa-times' style={{ color: 'red' }}></i>
                    )}</td>
                        <td>{order.isDelivered ? (
                      order.deliveredAt.substring(0, 10)
                    ) : (
                      <i className='fas fa-times' style={{ color: 'red' }}></i>
                    )}</td>
                        <td><Link to={`/order/${order._id}`}><button className="details">Details</button></Link></td>
                        </tr>
                    ))}
                    </tbody>
                    </table>
                </div>
            </div>
        </section>

    )
}

export default Profile

这是我写的减速器和动作的代码

//reducer
//state - userProfile
export const userGetProfileReducer = (state = {userData : {}} , action) => {
    switch(action.type) {
        case USER_GET_REQUEST :
            return { loading : true , state};
        case USER_GET_SUCCESS :
            return ({ loading : false , userData : action.payload });
        case USER_GET_ERROR : 
            return ({ loading : false , error : action.payload });
        default : 
            return state;
    }
}

//action - getUser
export const getUser = () => async(dispatch , getState) => {

    dispatch({type : USER_GET_REQUEST , loading : true })

    const headers = {headers : {
        'Content-Type' : 'application/json',
        'AUTHORIZATION' : `Bearer ${getState().userLogin.userData.token}`
    }}
    

    try {
        const {data} = await axios.get('http://localhost:5000/api/users/profile', headers);
        dispatch({type : USER_GET_SUCCESS , payload : data , loading : false});

    } catch (error) {
        console.log(error);
        dispatch({type : USER_GET_ERROR , loading : false , payload: error.response && error.response.data.message
          ? error.response.data.message
          : error.message})
    }
}

注意 - 订单功能运行良好。输入字段未使用响应数据进行更新。我确定我搞砸了 useEffect 依赖项。如果有人可以帮助我,那就太好了......

标签: reactjsreduxreact-reduxredux-formreducers

解决方案


推荐阅读