【问题标题】:React - unable to call props value inside a usecallback functionReact - 无法在 usecallback 函数中调用道具值
【发布时间】:2021-01-01 22:14:00
【问题描述】:
 import React,{useEffect,useCallBack} from 'react';

 ReactfunctionalComponent = ({className, DropDownValue, ...rest}) => {

     console.log(DropDownValue); //will log the value

     const getCustomers = useCallback(async ()=> {
         console.log(DropDownValue) // will not log the value (undefined)
     };
     
     useEffect(() => {
         console.log(DropDownvalue) // will not log the value (undefined)

         getCustomers();

     },[getCustomers]);

 return (
  <ListView/>
)

}

无法在回调函数中传递 DropDwonValue

可以在所有范围内访问该值,但不能在回调函数内访问,如果我使用方法错误或有任何替代用法可以使用下拉值,请向我建议。

DropdownValue 来自另一个组件。

如果您知道如何在组件渲染上触发函数,请建议,基本上,我需要在下拉值进入时进行API调用。

【问题讨论】:

  • 发布你的整个代码。
  • useCallback 应该始终使用依赖项数组调用,否则它什么也不做。

标签: reactjs axios react-hooks react-functional-component


【解决方案1】:

我假设组件第一次渲染时,DropDownValueundefined。这就是回调关闭的值。由于您没有告诉 React 回调依赖于 DropDownValue,因此当值更改时不会重新创建回调。

添加DropDownValue作为依赖:

const getCustomers = useCallback(async() => {
    console.log(DropDownValue);
}, [DropDownValue]);

基本上,我需要在下拉值进入时进行 API 调用。

这就是useEffect 允许您做的事情。您只需将值指定为依赖项,如documentation 中所述。 API 与useCallback 相同:

useEffect(async() => {
    console.log(DropDownValue);
}, [DropDownValue]);

【讨论】:

  • 我认为这可能有效,我会尽力让大家知道,非常感谢
【解决方案2】:
**You can do it in two ways:-**

//One way
const getCustomers = useCallback(async() => {
            console.log(DropDownValue);
        }, [DropDownValue]);
    
    useEffect(async() => {
       getCustomers();
    }, [getCustomers]);
    
        //Another

    const getCustomers = useCallback(async(DropDownValue) => {
        console.log(DropDownValue);
    }, []);

    useEffect(async() => {
           getCustomers(DropDownValue);
        }, [getCustomers,DropDownValue]);
    

【讨论】:

  • 谢谢,但是你不会得到useEffect里面的道具,我已经指出了
猜你喜欢
  • 2021-01-09
  • 1970-01-01
  • 2023-01-22
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多