【问题标题】:use context value as initial state value - react hooks使用上下文值作为初始状态值 - 反应钩子
【发布时间】:2020-06-05 15:32:35
【问题描述】:

我们可以使用上下文值在函数组件中启动状态变量吗?

在这里,我尝试使用来自上下文的值来启动组件状态。但是当上下文值改变时状态不会更新。


function Parent() {
  return (
    <ContextProvider>
      <Child />
    </ContextProvider>
  );
}

function Child() {
  const mycontext = useContext(Context);
  const [items, setItems] = useState(mycontext.users);
  console.log(mycontext.users, items); //after clicking fetch, => [Object, Object,...], [] both are not equal. why??????

  return (
    <>
      <button onClick={() => mycontext.fetch()}>fetch</button>
      {/* <button onClick={()=>mycontext.clear()} >Clear</button> */}
      {items.map(i => (
        <p key={i.id}>{i.name}</p>
      ))}
    </>
  );
}
/* context.js */
const Context = React.createContext();
function ContextProvider({ children }) {
  const [users, setUsers] = useState([]);

  function fetchUsers() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then(json => setUsers(json));
  }

  return (
    <Context.Provider
      value={{ users, fetch: fetchUsers, clear: () => setUsers([]) }}
    >
      {children}
    </Context.Provider>
  );
}

以上代码可以在codesandbox中测试。

我可以直接使用上下文值,但我想在组件内部维护状态。 如果我们不能使用上下文值启动状态值,如果我想从上下文中获取数据并且还想在内部维护状态,那么最好的方法是什么?

【问题讨论】:

    标签: reactjs react-hooks use-context


    【解决方案1】:

    useState 的参数只使用一次。

    您不需要在状态中复制上下文值,可以直接从上下文中使用它。

    如果你想这样做,你需要使用useEffect

    const [items, setItems] = useState(mycontext.users);
    
    useEffect(() => {
        setItems(mycontext.users);
    }, [mycontext.users]);
    

    updated demo

    【讨论】:

    • 谢谢。这行得通。如果我使用道具而不是上下文,例如const [items, setItems] = useState(props.users);,情况是否相同?即我应该使用useEffect 还是按照我的想法更新状态?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多