考虑以下事项:
我有一个带有嵌套子组件的父功能组件,
function Parent(){
const [isFlagTrue, setIsFlagIsTrue] = useState(false);
const handleFlagChange = (bool) => setIsFlagIsTrue(bool)
useEffect(() => {
console.log("isFlagTrue ", isFlagTrue);
}, [isFlagTrue])
return (
<Child handleFlagChange={handleFlagChange} />
)
}
在 Child 中,我进行异步调用以填充数据表;
import { useDispatch } from 'react-redux';
function Child({handleFlagChange}) {
const dispatch = useDispatch();
const componentIsMounted = useRef(true)
const [rows, setRows] = useState([]);
useEffect(() => {
if (currentProductItem && currentProductItem.value != null) {
dispatch(getClientVariables(currentProductItem.value)).then(r => {
rawData.current.Rows = r.payload;
dispatch(getClientVariableTypesAll(currentProductItem.value)).then(r => {
rawData.current.ClientDataVariableTypes = r.payload.map(r => {
return {
value: r.ClientDataVariableTypeID,
label: r.ClientDataVariableTypeName
}
});;
setRows(rawData.current.Rows);
console.log('rawData', rawData);
});
});
}
}, [currentProductItem, justSavedNewVariableTypes, justSavedGrid]);
}
useEffect(() => {
console.log("typeof handleFlagChange ", typeof handleFlagChange);
console.log("rows ", rows);
// if (componentIsMounted.current) {
// var flag = rows.some(item => item.ClientDataVariableTypeName == null)
// handleFlagChange(flag)
// }
if (Array.isArray(rows) && typeof handleFlagChange != 'undefined') {
console.log("foo ");
var flag = rows.some(item => item.ClientDataVariableTypeName == null)
handleFlagChange(flag)
}
}, []);
useEffect(() => {
return () => {
componentIsMounted.current = false
}
},[])
....other code & rendering
}
当行数组上的 isFlagTrue
函数的返回值在子级中验证了行时,我期望父级 useEffect 中的 some
控制台触发。
我尝试了两种解决方案,一种是通过使用 <Child/>
将 ref 设置为 true 来确保挂载 useRef()
(并使数据调用已满)。
在儿童中: const componentIsMounted = useRef(true)
useEffect(() => {
console.log("typeof handleFlagChange ", typeof handleFlagChange);
if (componentIsMounted.current) {
var flag = rows.some(item => item.ClientDataVariableTypeName == null)
handleFlagChange(flag)
}
}, []);
useEffect(() => {
return () => {
componentIsMounted.current = false
}
},[])
但我得到 TypeError: handleFlagChange is not a function
然后我尝试了:
useEffect(() => {
console.log("typeof handleFlagChange ", typeof handleFlagChange);
if (componentIsMounted.current && typeof handleFlagChange != 'undefined' && typeof handleFlagChange != 'undefined') {
console.log("foo ");
var flag = rows.some(item => item.ClientDataVariableTypeName == null)
handleFlagChange(flag)
}
}, []);
但这会产生:
typeof handleFlagChange undefined. <---In the Child
isFlagTrue false <--- In Parent
有什么想法吗?
答案 0 :(得分:1)
您是否考虑过为函数使用默认值并让 React 的正常流程来做您的工作?
function Child({handleFlagChange = () => {}})
让我知道这是否有效。
答案 1 :(得分:0)
我认为这是一个打字稿错误,说明子组件中的 handleFlagChange 类型未知。
这里有两个选项:
首先声明每个prop的类型,然后在函数中使用:
type PropsType = { handleFlagChange: () => void }
function Child({handleFlagChange}: PropsType)
或者尝试在函数本身中添加特定类型:
function Child({handleFlagChange: () => void})
其中 () => void
是 handleFlagChange 函数的类型。