将 useState 传递给孩子

时间:2021-02-18 22:02:46

标签: reactjs

我正在尝试使用以下代码将父组件的 useState 值传递给多个子组件。
应用程序

const [inSystem, setIn] = useState(false);
<Route exact path="/" functions={[inSystem, setIn]}  component={Loading} />

然后在我的 loading 组件中

const [inSystem, setIn] = props.functions
<NavLink to="/sol">
          <button onClick={() => {setIn(true)}}>
            <p >Enter System</p> 
          </button>
        </NavLink>

这是我在回答类似问题时找到的解决方案,我从这里复制了我的解决方案 codesandbox 但是我收到以下错误
“类型错误:未定义不可迭代(无法读取属性符号(Symbol.iterator))”

如果有人知道我做错了什么,我将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

您正在尝试将任意道具传递给路线(根据您的语法,我假设这是 react-router v4),但这些道具被忽略了。尝试使用 render 而不是 component

<Route
  exact
  path="/"
  render={(props) => {
    return (
      <Loading {...props} functions={[inSystem, setIn]} />
    );
  }}
/>