【问题标题】:React Redux - useState Hook not working as expectedReact Redux - useState Hook 未按预期工作
【发布时间】:2021-06-17 18:20:26
【问题描述】:

我在 redux 中有 2 个操作(都是异步的),我通过 dispatch 在我的功能组件中调用它们;第一个使用useEffect,第二个通过按钮单击。我想要做的是调度操作以从异步函数中检索它们,然后通过useState 在我的组件中使用它们。但是使用useState 不会渲染。

这是我的组件:

export default function Hello()
{

  const { first, second } = useSelector(state => state.myReducer);
  const dispatch = useDispatch();
  const fetchFirst = async () => dispatch(getFirst());
  const fetchSecond = async () => dispatch(getSecond());
  const fetchFixturesForDate = (date: Date) => dispatch(getFixturesForDate(date));

  const [superValue, setSuperValue] = useState('value not set');

  useEffect(() => {
    const fetch = async () => {
      fetchFirst();
      setSuperValue(first);
    };

    fetch();
  }, []);

  const getSecondOnClickHandler = async () =>
  {
    console.log('a')
    await fetchSecond();
    setSuperValue(second);
  }

  return (
    <div>
    <p>The super value should first display the value "first item" once retrieved, then display "second value" once you click the button and the value is retrieved</p>
    <p>Super Value: {superValue}</p>
    <p>First Value: {first}</p>
    <p>Second Value: {second}</p>
    <button onClick={async () => await getSecondOnClickHandler()}>Get Second</button>
    </div>
  )
}

superValue 永远不会呈现,即使我正在设置它,尽管来自 firstsecond 的值被检索并显示。

StackBlitz.

有什么帮助吗?

【问题讨论】:

    标签: reactjs redux react-hooks


    【解决方案1】:

    两个useEffects 中的firstsecond 的值是在组件安装时设置的(我猜那时它们是未定义的)。因此,在这两种情况下,您都将superValue 设置为该初始值。

    你有两个选择:

    1. fetchFirstfetchSecond返回第一个/第二个值,这样你就可以直接从执行的函数中检索它们,然后设置superValue:
     useEffect(() => {
        const fetch = async () => {
          const newFirst = await fetchFirst();
          setSuperValue(newFirst);
        };
    
        fetch();
      }, []);
    
    1. 添加单独的useEffects 来监听firstsecond 的变化
      useEffect(() => {
        setSuperValue(first)
      },[first])
    
      useEffect(() => {
        setSuperValue(second)
      },[second])
    

    【讨论】:

    • 谢谢!看来我用错了useEffect
    【解决方案2】:

    reducer 中的值不一定在调度操作时设置,例如在调用fetchFirst() 之后。还有你在await fetchSecond();中所做的await 没有帮助,因为 reducer 函数没有被执行。

    您可以添加useEffect 钩子并从其他方法中删除setSuperValue,但我认为代码变得相当复杂。 您首先要解决什么问题?

     useEffect(() => setSuperValue(first), [first]);
     useEffect(() => setSuperValue(second), [second]);
    
    useEffect(() => {
       const fetch = async () => {
         fetchFirst();
       };
       fetch();
     }, []);
    
     const getSecondOnClickHandler = async () => {
       console.log('a');
       await fetchSecond();
     };
    
    

    https://stackblitz.com/edit/react-ts-hsqd3x?file=Hello.tsx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 2018-06-28
      • 2018-03-12
      • 2017-03-01
      相关资源
      最近更新 更多