reactjs - 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 依赖项。如果有人可以帮助我,那就太好了......
解决方案
推荐阅读
- css - 如何更改 NPM 包中使用的样式?
- html - 如何使用 CSS 过渡更改文本的颜色?
- javascript - 在 javascript 中使用 if/else 更改文本颜色
- mongodb - 如何增加 WT allocation_size - MongoDB
- typescript - 什么是函数 makeObject(key,value){ return {[key]:value} 的打字稿签名;}?
- c# - 当为 Returns() 提供不同的值时,最小起订量返回相同的结果
- python - Python 3:获取与熊猫数据框某一列中的值关联的索引名称
- reactjs - 如何在状态中存储 API 响应的值?
- python-3.x - 如何只等待一定的时间让系统调用运行
- ruby-on-rails - 从今天开始在 ruby 中获取接下来 7 天的名称数组