Reactjs React-无法在usecallback函数中调用props值 import React,{useffect,useCallBack}来自“React”; ReactfunctionalComponent=({className,DropDownValue,…rest})=>{ console.log(DropDownValue);//将记录该值 const getCustomers=useCallback(异步()=>{ console.log(DropDownValue)//将不记录该值(未定义) }; useffect(()=>{ console.log(DropDownvalue)//将不记录该值(未定义) getCustomers(); },[getCustomers]); 返回( )
} 无法在回调函数内传递DropDwonValue 该值可以在所有范围内访问,但不能在回调函数内访问。如果我使用的方法错误,请向我建议,或者有任何其他用法可以使用下拉值 DropdownValue来自另一个组件Reactjs React-无法在usecallback函数中调用props值 import React,{useffect,useCallBack}来自“React”; ReactfunctionalComponent=({className,DropDownValue,…rest})=>{ console.log(DropDownValue);//将记录该值 const getCustomers=useCallback(异步()=>{ console.log(DropDownValue)//将不记录该值(未定义) }; useffect(()=>{ console.log(DropDownvalue)//将不记录该值(未定义) getCustomers(); },[getCustomers]); 返回( ),reactjs,axios,react-hooks,react-functional-component,Reactjs,Axios,React Hooks,React Functional Component,} 无法在回调函数内传递DropDwonValue 该值可以在所有范围内访问,但不能在回调函数内访问。如果我使用的方法错误,请向我建议,或者有任何其他用法可以使用下拉值 DropdownValue来自另一个组件 如果您知道如何在组件呈现上触发函数,请务必提出建议,基本上,当下拉值出现时,我需要进行API调用。我假设组件第一次呈现时,DropDownValue是未定义的。这是回调结束时的值。因为您没有告诉Reactllbacks依赖于DropDownValue,当值更改时,不会重新创建回调 添加D
如果您知道如何在组件呈现上触发函数,请务必提出建议,基本上,当下拉值出现时,我需要进行API调用。我假设组件第一次呈现时,
DropDownValue
是未定义的
。这是回调结束时的值。因为您没有告诉Reactllbacks依赖于DropDownValue
,当值更改时,不会重新创建回调
添加DropDownValue
作为依赖项:
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/>
)
基本上,我需要在输入下拉值时进行API调用
这就是useffect
允许您执行的操作。您只需将该值指定为依赖项,如中所述。API与useCallback
的API相同:
const getCustomers = useCallback(async() => {
console.log(DropDownValue);
}, [DropDownValue]);
请发布您的全部代码。useCallback应该始终使用依赖项数组进行调用,否则它将一事无成。谢谢您,但您不会得到useEffect中的道具,我已经指出,我认为这可能会起作用。我将尝试让您都知道,非常感谢
useEffect(async() => {
console.log(DropDownValue);
}, [DropDownValue]);
**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]);