1

我想要一个全局变量,我可以使用钩子在任何地方进行编辑。

在示例中,我有 2 个组件都使用相同的钩子。在我看来,它External toggle正在编辑自己的范围count,并且Internal Toggle也在改变自己的范围。

两个切换是否可以编辑相同的数据?

代码示例: https ://codesandbox.io/s/520zvyjwlp

index.js

function ChangeCount() {
  const { count, increment } = useCounter();
  return <button onClick={() => increment(!count)}>External Toggle</button>;
}

function App() {
  const { count, increment } = useCounter();
  return (
    <div>
      {`${count}`}
      <br />
      <ChangeCount />
      <br />
      <button onClick={() => increment(!count)}>Internal Toggle</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement); 

useCount.js

import { useState } from "react";
export default function useCounter() {
  const [count, setCount] = useState(false);
  const increment = (changeCount) => setCount(changeCount);
  return { count, increment };
}
4

2 回答 2

2

正如您所注意到的,自定义钩子用于共享有状态逻辑,而不是实际状态

如果您想共享一个状态,您可以使用该context功能并将对象中的count变量和increment函数传递给 的valuepropProvider并使用useContext.

例子

const { createContext, useContext, useState } = React;
const CounterContext = createContext();

function ChangeCount() {
  const { increment } = useContext(CounterContext);
  return <button onClick={increment}>External increment</button>;
}

function App() {
  const [count, setCount] = useState(0);
  function increment() {
    setCount(count + 1);
  }

  return (
    <CounterContext.Provider value={{ count, increment }}>
      <div>{count}</div>
      <ChangeCount />
      <button onClick={increment}>Internal increment</button>
    </CounterContext.Provider>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

于 2019-03-22T14:37:48.367 回答
1

要完成此任务,您应该通过上下文 API 共享您的状态,

考虑以下:

const CounterContext = React.createContext({
  count: 0,
  increment: () => null,
});

const changeCount = () => {
  const counter = useContext(CounterContext);

  return <button onClick={() => counter.increment(!counter.count)}>External Toggle</button>;
}

const App = () => {
  const { count, increment } = useCounter();
  return (
    <CounterContext.Provider value={{ count, increment }}>
      {`${count}`}
      <br />
      <ChangeCount />
      <br />
      <button onClick={() => increment(!count)}>Internal Toggle</button>
    </CounterContext.Provider>
  );
}

更多信息请访问:https ://reactjs.org/docs/context.html

于 2019-03-22T14:37:32.473 回答