如何将通过props传递的对象设置为钩子本地状态

问题描述 投票:0回答:1

传递道具设置为状态但无法访问内部属性

通过模型如下

let v = {
    "id": "6ccd12a3-802b-4ff6-ab6d-0f66f9df1e99",
    "mac": "a4:5e:60:f2:89:bf"
}

我按如下方式调用模型

<VisitorModal visitor={v}/>

模特在这里

从'react'导入React,{useState,useEffect};从'semantic-ui-react'导入{Modal,Form,Button};

const VisitorModal = ({ visitor }) => {

    const [ state, setState ] = useState({
        modalOpen: false,
        v: visitor,
    });

    const handleOnChange = (e) => {
        console.log(e.target.name);
        console.log(e.target.value);
        state[e.target.name] = e.target.value;
    }

    useEffect(() => {
        setState(prevState => ({
            ...prevState,
            v: visitor
        }));
      }, [visitor]);

    return (
        <Modal trigger={<Button onClick={ () => setState({ modalOpen: true }) }> View/Edit Visitor </Button>} centered={false}
                open={state.modalOpen}
                onClose={ () => setState({modalOpen: false}) }
                // closeOnEscape={closeOnEscape}
                // closeOnDimmerClick={closeOnDimmerClick}
            >
            {JSON.stringify(state)}
            {/* {JSON.stringify(state)} */}
                <Modal.Header> View/Edit Visitor </Modal.Header>
                <Modal.Content image>
                    {/* <Image wrapped size='medium' src='/images/avatar/large/rachel.png' /> */}
                    <Modal.Description>
                        {/* <Header>Default Profile Image</Header> */}
                        <Form>
                            <Form.Group widths="equal">
                                <Form.Input label="MAC" placeholder="mac" value={state.v.mac} onChange={handleOnChange} />
                                <Form.Input label="Name" placeholder="Name" value={state.v.name} onChange={handleOnChange} />
                            </Form.Group>
                            <Form.Group>
                                <Form.Button >Save</Form.Button>
                                {/* <Form.Button disabled={!state.orgName}>Save</Form.Button> */}
                                <Form.Button onClick={() => setState({ modalOpen: false })}>Cancel</Form.Button>
                            </Form.Group>
                        </Form>
                    </Modal.Description>
                    {/* <button >click</button> */}

                </Modal.Content>
            </Modal>
    )
}

export default VisitorModal;

error is TypeError: Cannot read property 'mac' of undefined

reactjs react-hooks
1个回答
1
投票

原因是因为您没有在初始状态对象中设置v的值,也不在事件处理程序中设置值。 useState()不合并对象值,它会覆盖它们。因此,您有两个选择:使用useReducer,或为modalOpenv使用单独的状态对象。

这应该使用后一个选项修复它,假设你适当地更新你的render()方法:

const VisitorModal = ({ visitor }) => {
  const [ modalOpen, setModalOpen ] = useState(false);
  const [ v, setV ] = useState(visitor);

  // Update `v` when the visitor prop changes.
  useEffect(() => {
    setV(visitor);
  }, [visitor]);
  const handleChange = e => setV({ ...v, [e.target.name]: e.target.value });
  return (
       <Form.Input label="MAC" placeholder="mac" value={v.mac} onChange={handleChange} />
  );
}

您的事件处理程序现在可以独立地引用setV()setModalOpen()

© www.soinside.com 2019 - 2024. All rights reserved.