react TypeError:无法读取未定义的属性“id”
2021-03-25
5757
从“订单”组件,将订单 ID 发送到“更新”组件。然后尝试更新包含该 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 }
});
}
2个回答
尝试类似:
useEffect(() => {
if(location?.state?.id)
setOrderId(location.state.id);
}, [location?.state?.id]);
Vrushali Bhosale
2021-03-25
尝试一下:
useEffect(() => {
setOrderId(location.state?.id);
..........
}, [location]);
crispengari
2021-03-25