【问题标题】:React, Typescript, Axios consume response?React、Typescript、Axios 消耗响应?
【发布时间】:2020-11-23 21:09:38
【问题描述】:

请问如何将函数的结果写在State中?

const [car, setCars] = useState<ICars[]>([]);

useEffect(() =>{

  const data = fetchCars(params.cartyp);

  //The return type of this function is:
  Promise<AxiosResponse<ICars[]> | undefined>
  
  setCars(data);  // >> There is an error:

}

错误: TS2345:'Promise 类型的参数 | undefined>' 不能分配给“SetStateAction”类型的参数。

【问题讨论】:

    标签: reactjs typescript axios


    【解决方案1】:

    fetchCars 是异步的并返回一个promise,你必须等待结果出现:

    const [car, setCars] = useState<ICars[]>([]);
    
    useEffect(() =>{
    
      fetchCars(params.cartyp).then(data => {
        if(data) setCars(data);
      });
      
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-24
    • 2021-02-21
    • 2020-10-04
    • 2018-04-12
    • 2021-07-27
    • 1970-01-01
    • 2021-06-30
    • 2018-03-18
    相关资源
    最近更新 更多