Reactjs 在UseEffect返回后使用useState初始化:可能吗?

Reactjs 在UseEffect返回后使用useState初始化:可能吗?,reactjs,use-effect,Reactjs,Use Effect,我有两个问题 使用useEffect调用api: React.useEffect(() => { //API get call },[]); api的结果存储在数组中 问题1:我知道useEffect是一种异步方法,但在useEffect返回后,有没有办法使用useState初始化下拉列表的值 问题2:如何使用数组的值初始化forEach循环中的值?在useffect中调用API后,调用要保存到的useState的设置状态。例如: const [state, setState] =

我有两个问题

使用useEffect调用api:

React.useEffect(() => {
  //API get call
},[]);
api的结果存储在数组中

问题1:我知道useEffect是一种异步方法,但在useEffect返回后,有没有办法使用useState初始化下拉列表的值


问题2:如何使用数组的值初始化forEach循环中的值?

useffect
中调用API后,调用要保存到的
useState
的设置状态。例如:

const [state, setState] = useState([]);

const someFetch = async () => {
 // using JS fetch API
 const result = await fetch("getFetchSomeData");
 // assuming the state is in the form of an array
 setState(result.json())
}

useEffect(() => }{
   someFetch();
});

return (
  // rendering the array of fetched state this will update on next render after fetch
  <div>{state}</div>
):
const[state,setState]=useState([]);
const someFetch=async()=>{
//使用jsfetchapi
const result=等待获取(“getFetchSomeData”);
//假设状态是数组的形式
setState(result.json())
}
useEffect(()=>}{
someFetch();
});
返回(
//渲染已获取状态的数组在获取后的下一次渲染时,此属性将更新
{state}
):

useffect
中调用API后,调用要保存到的
useState
的设置状态。例如:

const [state, setState] = useState([]);

const someFetch = async () => {
 // using JS fetch API
 const result = await fetch("getFetchSomeData");
 // assuming the state is in the form of an array
 setState(result.json())
}

useEffect(() => }{
   someFetch();
});

return (
  // rendering the array of fetched state this will update on next render after fetch
  <div>{state}</div>
):
const[state,setState]=useState([]);
const someFetch=async()=>{
//使用jsfetchapi
const result=等待获取(“getFetchSomeData”);
//假设状态是数组的形式
setState(result.json())
}
useEffect(()=>}{
someFetch();
});
返回(
//渲染已获取状态的数组在获取后的下一次渲染时,此属性将更新
{state}
):
问题1

我可能会这样做:

function MyComponent() {
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState(undefined);
  
  useEffect(() => {
    async function getData() {
      setIsLoading(true);
      const data = await /* API call */
      setData((prevVal) => data);
      setIsLoading(false);
    }

    getData();
  }, []);
  
  if (loading) return <h1>Loading...</h1>;

  if (!loading && !data) return <h1>Error!</h1>;

  return (
    /* your component */
  );
}

问题1

我可能会这样做:

function MyComponent() {
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState(undefined);
  
  useEffect(() => {
    async function getData() {
      setIsLoading(true);
      const data = await /* API call */
      setData((prevVal) => data);
      setIsLoading(false);
    }

    getData();
  }, []);
  
  if (loading) return <h1>Loading...</h1>;

  if (!loading && !data) return <h1>Error!</h1>;

  return (
    /* your component */
  );
}

问题1:我知道useEffect是一种异步方法,但在useEffect返回后,有没有办法使用useState初始化下拉列表的值

不,我们无法在useEffect运行后初始化useState
useffect
hook总是在第一次渲染之后和每次更新之后运行。我们还需要在第一次渲染时具有状态的初始化值。然后,当useEffect运行时,我们可以简单地通过设置来更新状态

function App(){

 const [stateVariable, setStateVariable] = useState(null);
 
 useEffect(() => {

   async function fetchApiCall(){
    fetch('http://example.com/movies.json')
       .then(response => response.json())
       .then(data => setStateVariable(data));
   }
  fetchApiCall(); // function call

 },[]);

}

问题2:如何使用数组的值初始化forEach循环中的值

现在我们在state变量中有了数据。最有可能的是,来自API的数据位于对象数组[JSON]中

Array.prototype.map()
函数在这里可能会有所帮助。据mdn称

map()方法创建一个新数组,其中填充了对调用数组中的每个元素调用所提供函数的结果


函数进程组件(元素、索引){
返回
  • {element}
  • ; } const newData=data.map(processeachement); //现在,newData是一个“JSX.Elements”数组。记住,不是一个对象数组。
    最后的代码如下所示

    function App() {
      const [stateVariable, setStateVariable] = useState(null);
    
      useEffect(() => {
        async function fetchApiCall() {
          fetch("http://example.com/movies.json")
            .then((response) => response.json())
            .then((data) => setStateVariable(data));
        }
        fetchApiCall(); // function call
      }, []);
    
      function processEachElement(element, index) {
        return <li key={index}>{element}</li>;
      }
    
      const newData = data.map(processEachElement);
    
      return <ul>{newData}</ul>;
    }
    
    
    函数应用程序(){
    常量[stateVariable,setStateVariable]=useState(null);
    useffect(()=>{
    异步函数fetchApiCall(){
    取回(“http://example.com/movies.json")
    .then((response)=>response.json())
    .然后((数据)=>setStateVariable(数据));
    }
    fetchApiCall();//函数调用
    }, []);
    函数进程组件(元素、索引){
    返回
  • {element}
  • ; } const newData=data.map(processeachement); 返回
      {newData}
    ; }
    问题1:我知道useEffect是一种异步方法,但在useEffect返回后,有没有办法使用useState初始化下拉列表的值

    不,我们无法在useEffect运行后初始化useState
    useffect
    hook总是在第一次渲染之后和每次更新之后运行。我们还需要在第一次渲染时具有状态的初始化值。然后,当useEffect运行时,我们可以简单地通过设置来更新状态

    function App(){
    
     const [stateVariable, setStateVariable] = useState(null);
     
     useEffect(() => {
    
       async function fetchApiCall(){
        fetch('http://example.com/movies.json')
           .then(response => response.json())
           .then(data => setStateVariable(data));
       }
      fetchApiCall(); // function call
    
     },[]);
    
    }
    
    
    问题2:如何使用数组的值初始化forEach循环中的值

    现在我们在state变量中有了数据。最有可能的是,来自API的数据位于对象数组[JSON]中

    Array.prototype.map()
    函数在这里可能会有所帮助。据mdn称

    map()方法创建一个新数组,其中填充了对调用数组中的每个元素调用所提供函数的结果

    
    函数进程组件(元素、索引){
    返回
  • {element}
  • ; } const newData=data.map(processeachement); //现在,newData是一个“JSX.Elements”数组。记住,不是一个对象数组。
    最后的代码如下所示

    function App() {
      const [stateVariable, setStateVariable] = useState(null);
    
      useEffect(() => {
        async function fetchApiCall() {
          fetch("http://example.com/movies.json")
            .then((response) => response.json())
            .then((data) => setStateVariable(data));
        }
        fetchApiCall(); // function call
      }, []);
    
      function processEachElement(element, index) {
        return <li key={index}>{element}</li>;
      }
    
      const newData = data.map(processEachElement);
    
      return <ul>{newData}</ul>;
    }
    
    
    函数应用程序(){
    常量[stateVariable,setStateVariable]=useState(null);
    useffect(()=>{
    异步函数fetchApiCall(){
    取回(“http://example.com/movies.json")
    .then((response)=>response.json())
    .然后((数据)=>setStateVariable(数据));
    }
    fetchApiCall();//函数调用
    }, []);
    函数进程组件(元素、索引){
    返回
  • {element}
  • ; } const newData=data.map(processeachement); 返回
      {newData}
    ; }
    Sure,在
    useffect
    回调中设置状态,它将在下次重新渲染时对您可用。Sure,在
    useffect
    回调中设置状态,它将在下次重新渲染时对您可用。