如何在 useEffect 中调度? [英] How to dispatch in useEffect?

查看:26
本文介绍了如何在 useEffect 中调度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 useEffect 中使用 useState 设置状态没有问题,代码如下:

I tried to set a state using useState inside useEffect with no problem, code as follows:

import React, {useState, useEffect} from 'react';

const Banner = () => {
  const [title, setTitle] = useState([]);
  
  useEffect(() => {
    async function fetchData() {
      const api = 'some api url';
      let response = await fetch(api);
      response = await response.json();
      setTitle(response.title);
    }
    fetchData();
  })
}

export default Banner;

现在我想做同样的事情,但是使用 useReducer,我尝试将上面的代码修改为以下内容,但没有成功:

Now I'd like to do the same thing but with useReducer, I tried to modify the above code to the following but no luck:

import React, {useState, useEffect} from 'react';

const bannerReducer = (state, action) => {
  switch(action.type) {
    case 'setTitle':
      return {
        ...state,
        title: state.title
      }
  }
}

const [state, dispatch] = useReducer(bannerReducer, {title: []});

const Banner = () => {
  const [title, setTitle] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const api = 'some api url';
      let response = await fetch(api);
      response = await response.json();
      dispatch({type: 'setTitle', response.title});
    }
    fetchData();
  })
}

export default Banner;

在这种情况下如何使用 useReducer?

How can I use useReducer in this case?

推荐答案

在这种情况下,您正在使用与之前相同的状态属性设置 reducer:

You're setting the reducer with the same state property as it was before in this case you're basically doing:

title: state.title

并且由于您的默认状态是带有空数组值的标题,因此您无需更改任何内容.

And since your default state is a title with an empty array value you're not changing anything.

你需要在你的 reducer 中使用 action 参数来完成你想要的:

You need to use the action argument in your reducer to accomplish what you want:

const bannerReducer = (state, action) => {
 switch(action.type) {
  case 'setTitle':
   return {
    ...state,
    title: action.title
   }
  }
}

你的派遣应该是这样的:

And your dispatch should be something like this:

dispatch({type: 'setTitle', title: response.title});

这篇关于如何在 useEffect 中调度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆