繁体   English   中英

从多个子组件更新父 state 的反应挂钩

[英]React hooks updating a parent state from multiple child components

我的父组件复制子组件 onClick。 我的目标是针对每个子组件,在用户输入 select 值和文本字段值后,它将附加到父组件的 map 值上。 I used an approach that passes in a function that edits the map object, but after console logging I realize it just resets the map value for every child component submission. 有关如何解决此问题的任何建议?

ex) if user picks instagram with 'www.instagram.com/user' in one child component and facebook with 'www.facebook.com/user' in the other child component, the parent component will ultimately have a map of both key value对。

父组件 (Admin.js)

const Admin = () => {
  const links = new Map();
  const [newLink, setNewLink] = useState([]);

  const addLinkToMap = (type, url) => {
    links.set(type, url);
  }

  return (
    <>
      {newLink ? newLink.map(child => child) : null}
        <Button onClick={() => {
           setNewLink(
             [ ...newLink, 
               <AddNewLink key={Math.random()} linkMap={addLinkToMap}/>
             ]
        )}}>
          Add new social media
        </Button>
    </>
  );
}

export default Admin;

子组件 (AddNewLink.js)

const AddNewLink = props => {
  const [socialMedia, setSocialMedia] = useState('');
  const [url, setUrl] = useState('');
  const linkMap = props.linkMap;

  const handleSubmit = () => {
    linkMap(socialMedia, url);
  }

  return (
    <>
      <FormControl>
        <InputLabel>Select Social Media</InputLabel>
          <Select
            value={socialMedia}
            onChange={e => {setSocialMedia(e.target.value)}}
          >
            <MenuItem value={'facebook'}>Facebook</MenuItem>
            <MenuItem value={'instagram'}>Instagram</MenuItem>
            <MenuItem value={'tiktok'}>TikTok</MenuItem>
          </Select>
      </FormControl>
      <form>
        <TextField label="Enter link" onChange={e => {setUrl(e.target.value)}}/>
      </form>
      <div>
        <Button onClick={() => handleSubmit()}>Submit</Button>
      </div>
    </>
  )
}

export default AddNewLink;

问题是,每当您通过调用setLink设置 state 时,您的 function 就会再次被调用,这意味着每次useState更改使用调用状态以解决此问题时,变量links的值都会重置为links map 创建一个变量。 像这样:

const [links, setLinks] = useState({});

const addLinkToMap = (type, url) => {
    setLinks({
       ...links,
       type: url
     });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM