是否可以使用React中的useState()钩子在组件之间共享状态?

时间:2018-11-23 18:40:12

标签: javascript reactjs react-hooks

我正在实验React中的新Hook功能。考虑到我有以下两个组件(使用React Hooks)-

tab

Hooks声称解决了在组件之间共享有状态逻辑的问题,但是我发现const HookComponent = () => { const [username, setUsername] = useState('Abrar'); const [count, setState] = useState(); const handleChange = (e) => { setUsername(e.target.value); } return ( <div> <input name="userName" value={username} onChange={handleChange}/> <p>{username}</p> <p>From HookComponent: {count}</p> </div> ) } const HookComponent2 = () => { const [count, setCount] = useState(999); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } HookComponent之间的状态不可共享。例如,HookComponent2count的更改不会呈现HookComponent2中的更改。

是否可以使用HookComponent钩子在组件之间共享状态?

6 个答案:

答案 0 :(得分:17)

如果您指的是组件状态,则挂钩将无法帮助您在组件之间共享它。组件状态是组件本地的。如果您的州生活在上下文中,那么useContext钩子会很有帮助。

从根本上说,我认为您误解了“在组件之间共享有状态逻辑”这一行。有状态逻辑不同于状态。有状态逻辑是您用来修改状态的东西。例如,某个组件在componentDidMount()中订阅商店,而在componentWillUnmount()中取消订阅。这种订阅/取消订阅行为可以在钩子中实现,而需要这种行为的组件可以只使用该钩子。

如果您要在组件之间共享状态,则有多种方法可以共享状态,每种方法各有优点:

1。提升状态

将状态提升到两个组件的共同祖先组件。

function Ancestor() {
    const [count, setCount] = useState(999);
    return <>
      <DescendantA count={count} />
      <DescendantB count={count} />
    </>;
  }

这种状态共享方法与使用状态的传统方法从根本上没有什么不同,钩子只是为我们提供了一种声明组件状态的不同方法。

2。上下文

如果后代在组件层次结构中过于深入,并且您不想将状态传递到太多层次,则可以使用Context API

在子组件中有一个useContext钩子可供您利用。

3。外部状态管理解决方案

状态管理库,例如Redux或Mobx。然后,您的状态将位于React外部的商店中,组件可以连接/订阅该商店以接收更新。

答案 1 :(得分:3)

doc的状态:

  

我们从React导入useState Hook。它使我们可以将局部状态保留在功能组件中。

没有提到状态可以在组件之间共享,useState钩子为您提供了一种在一条指令中声明状态字段及其对应设置器的更快方法。

答案 2 :(得分:2)

有可能没有任何外部状态管理库。只需使用简单的observable实现:

function makeObservable(target) {
  let listeners = []; // initial listeners can be passed an an argument aswell
  let value = target;

  function get() {
    return value;
  }

  function set(newValue) {
    if (value === newValue) return;
    value = newValue;
    listeners.forEach((l) => l(value));
  }

  function subscribe(listenerFunc) {
    listeners.push(listenerFunc);
    return () => unsubscribe(listenerFunc); // will be used inside React.useEffect
  }

  function unsubscribe(listenerFunc) {
    listeners = listeners.filter((l) => l !== listenerFunc);
  }

  return {
    get,
    set,
    subscribe,
  };
}

然后创建商店并通过使用subscribe中的useEffect使其挂接以做出反应:

const userStore = makeObservable({ name: "user", count: 0 });

const useUser = () => {
  const [user, setUser] = React.useState(userStore.get());

  React.useEffect(() => {
    return userStore.subscribe(setUser);
  }, []);

  const actions = React.useMemo(() => {
    return {
      setName: (name) => userStore.set({ ...user, name }),
      incrementCount: () => userStore.set({ ...user, count: user.count + 1 }),
      decrementCount: () => userStore.set({ ...user, count: user.count - 1 }),
    }
  }, [user])

  return {
    state: user,
    actions
  }
}

那应该可行。无需React.Context或提升状态

答案 3 :(得分:2)

可以使用useBetween钩子来实现。

See in codesandbox

import React, { useState } from 'react';
import { useBetween } from 'use-between';

const useShareableState = () => {
  const [username, setUsername] = useState('Abrar');
  const [count, setCount] = useState(0);
  return {
    username,
    setUsername,
    count,
    setCount
  }
}


const HookComponent = () => {
  const { username, setUsername, count } = useBetween(useShareableState);

  const handleChange = (e) => {
    setUsername(e.target.value);
  }

  return (
    <div>
      <input name="userName" value={username} onChange={handleChange}/>
      <p>{username}</p>
      <p>From HookComponent: {count}</p>
    </div>
  )
}


const HookComponent2 = () => {
  const { count, setCount } = useBetween(useShareableState);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

我们将React钩子状态逻辑从HookComponent移到useShareableState。 我们在每个组件中使用useShareableState来调用useBetween

useBetween是调用任何挂钩的一种方法。但是这样一来,状态将不会存储在React组件中。 对于相同的钩子,调用的结果将相同。因此,我们可以在不同的组件中调用一个钩子,并在一种状态下协同工作。更新共享状态时,使用共享状态的每个组件也会被更新。

答案 4 :(得分:1)

您仍然需要将状态提升到HookComponent1和HookComponent2的祖先组件。这就是您之前共享状态的方式,而最新的hook API对此没有任何更改。

答案 5 :(得分:1)

我创建了hooksy,可以让您完全做到这一点-https://github.com/pie6k/hooksy

import { createStore } from 'hooksy';

interface UserData {
  username: string;
}

const defaultUser: UserData = { username: 'Foo' };

export const [useUserStore] = createStore(defaultUser); // we've created store with initial value.
// useUserStore has the same signature like react useState hook, but the state will be shared across all components using it

以及以后的任何内容

import React from 'react';

import { useUserStore } from './userStore';

export function UserInfo() {
  const [user, setUser] = useUserStore(); // use it the same way like useState, but have state shared across any component using it (eg. if any of them will call setUser - all other components using it will get re-rendered with new state)

  function login() {
    setUser({ username: 'Foo' })
  }

  return (
    <div>
      {!user && <strong>You're logged out<button onPress={login}>Login</button></strong>}
      {user && <strong>Logged as <strong>{user.username}</strong></strong>}
    </div>
  );
}
相关问题