Javascript 如何有效地调度?
我尝试在Javascript 如何有效地调度?,javascript,reactjs,use-effect,use-state,use-reducer,Javascript,Reactjs,Use Effect,Use State,Use Reducer,我尝试在useffect内部使用useState设置状态,没有问题,代码如下: import React,{useState,useffect}来自“React”; 常量横幅=()=>{ const[title,setTitle]=useState([]); useffect(()=>{ 异步函数fetchData(){ const api='一些api url'; let response=等待获取(api); response=wait response.json(); setTitle(
useffect
内部使用useState
设置状态,没有问题,代码如下:
import React,{useState,useffect}来自“React”;
常量横幅=()=>{
const[title,setTitle]=useState([]);
useffect(()=>{
异步函数fetchData(){
const api='一些api url';
let response=等待获取(api);
response=wait response.json();
setTitle(response.title);
}
fetchData();
})
}
导出默认横幅代码>您的useReducer
调用不在函数内,因此不会附加到函数。
可以这样称呼:
dispatch({type: 'setTitle', title: response.title});
const Banner=()=>{
const[title,setTitle]=useState([]);
const[state,dispatch]=useReducer(bannereducer,{title:[]});
useffect(()=>{
异步函数fetchData(){
const api='一些api url';
let response=等待获取(api);
response=wait response.json();
分派({type:'setTitle',response.title});
}
fetchData();
}, []);
}
还要记住,每次调用Banner
函数时,useffect
都会运行。考虑在HooKS教程中添加一个依赖数组:< p>您设置的还原器和以前一样的状态属性,在这种情况下,基本上是:
title: state.title
由于您的默认状态是一个带有空数组值的标题,所以您不会更改任何内容
您需要在reducer中使用action参数来完成您想要的:
const bannerReducer = (state, action) => {
switch(action.type) {
case 'setTitle':
return {
...state,
title: action.title
}
}
}
你的任务应该是这样的:
dispatch({type: 'setTitle', title: response.title});
此外,Dispatch应该是Dispatch({type:'setTitle',title:response.title});在reducer中,返回的应该是title:action.title,而不是title:state.title。另外,在不处理操作时,您应该确保始终返回当前状态。并且在useffect()
的第二个参数中添加一个[]
,因为这会导致无限循环。