使用 useEffect 存储响应以避免使用反应钩子重新渲染

时间:2021-06-02 14:04:01

标签: reactjs react-hooks

我正在使用 React 钩子并试图弄清楚,我应该如何将 api 调用 response.data._embedded.assets 的响应存储在状态变量中。

由于重新渲染,使用 setAssets(response.data._embedded.assets); 不起作用。所以我决定使用 useEffect 如下面的代码所示,但这违反了反应规则 hooks -Hooks 只能在函数组件的主体内部调用。我知道 useEffect 应该根据 react 钩子在外部定义,但是我将如何将响应存储在状态变量中?请指教。

const [selectedTabIndex, setselectedTabIndex] = useState(0);
    const [assets,setAssets] = useState([]);

  
    
    let companyCategory;
    axios
    .get(url, {
        params: {
            assetCategoryId: selectedTabIndex
        }
    }).then(response => {
    if (sessionStorage.getItem('companyCategory') !== null) {
        companyCategory = JSON.parse(sessionStorage.getItem('companyCategory') )
      
    }
    console.log("Inside response of web api call");
    console.log(response.data._embedded.assets);
    useEffect(() => {
        // Should not ever set state during rendering, so do this in useEffect instead.
        setAssets(response.data._embedded.assets);
      }, []);
    //setAssets(response.data._embedded.assets);
   
}).catch(err => console.log(err));

在类组件中,上面的状态变量声明在响应中是这样的:

this.setState({
        companyCategory: companyCategory,
         assets: response.data._embedded.assets
     })

3 个答案:

答案 0 :(得分:2)

我会将整个 get 请求放在 useEffect 中。

    const [selectedTabIndex, setselectedTabIndex] = useState(0);
    const [assets,setAssets] = useState([]);

    useEffect(() => {
        // Should not ever set state during rendering, so do this in useEffect instead.
        
    
    let companyCategory;
    axios
    .get(url, {
        params: {
            assetCategoryId: selectedTabIndex
        }
    }).then(response => {
    if (sessionStorage.getItem('companyCategory') !== null) {
        companyCategory = JSON.parse(sessionStorage.getItem('companyCategory') )
      
    }
    console.log("Inside response of web api call");
    console.log(response.data._embedded.assets);
    
    setAssets(response.data._embedded.assets);
   
}).catch(err => console.log(err));
 
}, []);

答案 1 :(得分:0)

如果一个组件改变时不需要渲染,不要把它置于状态。您可以在组件中使用模块范围变量并使用它。

有了类组件,也可以放在this

答案 2 :(得分:0)

如果您不想使用数据,为什么要获取数据, 我们也不能在函数内部使用 react hooks

  • 从 React 函数组件调用 Hooks
  • 从自定义 Hooks 调用 Hooks
相关问题