问题描述
从“orders”组件发送一个订单id到“update”组件。然后尝试更新包含 id 的订单的“状态”。
在控制台中记录 id 值有效,但不能使用它设置状态。
“更新”组件:
const UpdateStatus = (props) => {
const location = useLocation();
const [orderId,setorderId] = useState(null);
const [status,setStatus] = useState("pending");
useEffect(() => {
setorderId(location.state.id); // errors here
console.log(location.state.id) // but gives a valid id
},[location]);
const handleChange = e => {
setStatus(e.target.value);
console.log(e.target.value)
}
const history = useHistory();
const handleClick = () => {
if (orderId){
axios.patch(`http://localhost:5000/orders/change-status/${orderId}`,{status: status},{withCredentials: true})
.then((res) => {
console.log(res);
history.push("/get-orders");
})
}
}
return (
<div>
<h2> Update Order Status </h2>
<form>
<label>Change status to: </label>
<select name="status" id="order-status" onChange={handleChange}>
<option value="pending">Pending</option>
<option value="accepted">Accepted</option>
<option value="delivered">Delivered</option>
</select>
<br/><br/>
<input type="submit" value="Submit" onClick={handleClick}/>
</form>
</div>
);
}
“订单”组件:
const handleClick = orderId => {
history.push({
pathname: '/update-status',state: { id: orderId }
});
}
解决方法
尝试类似:
useEffect(() => {
if(location?.state?.id)
setOrderId(location.state.id);
},[location?.state?.id]);
,
试试这个:
useEffect(() => {
setOrderId(location.state?.id);
..........
},[location]);