【问题标题】:react TypeError: Cannot read property 'id' of undefined反应TypeError:无法读取未定义的属性'id'
【发布时间】:2021-06-22 01:58:13
【问题描述】:

从“订单”组件,将订单 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 }
        });
    }

【问题讨论】:

    标签: reactjs react-hooks react-state


    【解决方案1】:

    试试这个:

    useEffect(() => {
            setOrderId(location.state?.id);  
           .......... 
     }, [location]); 
    

    【讨论】:

      【解决方案2】:

      尝试类似:

      useEffect(() => {
       if(location?.state?.id)
          setOrderId(location.state.id); 
       }, [location?.state?.id]);
      

      【讨论】:

      • 谢谢。你能解释一下为什么它仍然可以在控制台记录时给出这个错误吗?
      猜你喜欢
      • 1970-01-01
      • 2022-09-27
      • 2020-09-07
      • 2021-07-10
      • 2017-01-01
      • 2021-01-16
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多