function Route()
{
const [Items, setItems] = useState([]);
const [status, setQuotestatus] = useState(true);
const [quotation, setQuotation] = useState({quoteNo: "", type: "Project", quoteDate: "", validity: "", total: 0});
const callback = useCallback((Items,quotation) =>
{
setItems(Items);
setQuotation(quotation);
console.log(status)
setQuotestatus(!status);
console.log(quotation,status);
}, [],);
if(status)
{
return (<Quote allItems={Items} quote={quotation} parentCallback={callback} />);
}
else
{
return (<Documents Items={Items} quote={quotation} parentCallback={callback} />);
}
}
export default Route;
我使用useCallBack来切换和传递具有相同父组件<Route />
的2个子组件之间的参数。默认情况下,第一次切换是使用使用回调工作,但是当我试图从下一个组件调用这个相同的useCallback时,它正在调用钩子,但组件没有转移到下一个。也就是说我可以先到<Quote />
,然后再到<Documents />
。但无法从<Documents />
移回<Quote />
<Quote />
按钮
<button type="button" className="btn btn-primary" onClick={(e) => {e.preventDefault(); parentCallback(storedItems, {quoteNo: quoteNo, type: type, quoteDate: quoteDate, validity: validity, total: total})}} >
Preview
</button>
<Documents />
按钮
<div className="col">
<button type="button" className="btn btn-primary" onClick={(e) => {e.preventDefault(); parentCallback(storedItems, {quoteNo: quote.quoteNo, type: quote.type, quoteDate: quote.quoteDate, validity: quote.validity, total: quote.total})}} >Back</button>
</div>
因为您在useCallback
中使用status
,但您没有将其传递到依赖项中。所以status总是初始值。
在这种情况下你应该使用setState回调:
const callback = useCallback((Items,quotation) =>
{
setItems(Items);
setQuotation(quotation);
setQuotestatus(preStatus => !preStatus );
}, [],);
你应该把console.log
放到useEffect
中,因为状态只有在组件重新渲染时才有新值
useEffect(() => {
console.log(quotation,status);
}, [quotation, status])
不要在回调中调用setState,而是使用外部函数来更改状态
const [Items, setItems] = useState([]);
const [status, setQuotestatus] = useState(true);
const [quotation, setQuotation] = useState({quoteNo: "", type: "Project", quoteDate: "", validity: "", total: 0});
function preState(){
setQuotestatus(!status);
}
const callback = useCallback((Items,quotation) =>
{
setItems(Items);
setQuotation(quotation);
preState();
}, [Items, quotation],);