[英]React re-render parent from child component not working
我有一個父組件(DevicePage),它加載多個子組件(設備)。 在子組件中,我有用於簽入和簽出設備的按鈕。 當我單擊 DevicePage 上的按鈕時,頁面不會重新呈現,按鈕狀態也不會改變。
我嘗試了一些建議的答案,您將 function 傳遞給孩子,孩子可以調用以更新父級上的 state (請參閱此處如何從子組件重新渲染父組件),但在我的情況下它不起作用不知道為什么。
這是我所擁有的:
家長
const [devices, setDevices] = useState();
const [count, setCount] = useState(0);
useEffect(() => {
setCount(1)
DeviceService.getAll()
.then(res => {
if(res.data.length > 0) {
setDevices(res.data);
}
});
}, [])
function checkoutDevice(id) {
console.log("About to checkout device");
DeviceService.checkoutDevice(id)
.then(res => {
console.log("Device checked out")
})
.catch(err => "Error checking out device: " + err);
}
function checkinDevice(id) {
DeviceService.checkinDevice(id)
.then(res => {
console.log("Device checked in")
})
.catch(err => "Error checking out device: " + err);
}
function devicesList() {
if(devices) {
return devices.map(currDevice => {
return <Device device={currDevice} checkoutDevice={checkoutDevice} checkinDevice={checkinDevice} key={currDevice._id} />;
});
}
}
return (
<div>
<table className="table">
<thead className="thead-light">
<tr>
<td>Tag</td>
<td>Category</td>
<td>Make</td>
<td>Model</td>
</tr>
</thead>
<tbody>
{devicesList()}
</tbody>
</table>
</div>
)
}
孩子
return (
<tr>
<td><Link to={"/devices/" + props.device._id}>{props.device.tag}</Link></td>
<td>{props.device.category}</td>
<td>{props.device.make}</td>
<td>{props.device.modelName}</td>
{
props.device.available?
<>
<td>
<button type="button" className="btn btn-primary" onClick={() => {props.checkoutDevice(props.device._id)}}>Checkout</button>
</td>
</>
:
<>
<td>
<button type="button" className="btn btn-primary" onClick={() => {props.checkinDevice(props.device._id)}}>Checkin</button>
</td>
</>
}
{
currUser.isAdmin?
<>
<td>
<Link to={{pathname: "/devices/edit/" + props.device._id,
state: {
tag: props.device.tag
}}}>
edit
</Link>
</td>
</>
:
null
}
</tr>
)
您的問題是“頁面不會重新呈現並且按鈕狀態不會改變。”,我的假設是當您單擊“結帳”按鈕時,您希望它更改為“簽入”按鈕,反之亦然。 查看 Device 組件中的這個代碼塊:
{
props.device.available?
<>
<td>
<button type="button" className="btn btn-primary" onClick={() => {props.checkoutDevice(props.device._id)}}>Checkout</button>
</td>
</>
:
<>
<td>
<button type="button" className="btn btn-primary" onClick={() => {props.checkinDevice(props.device._id)}}>Checkin</button>
</td>
</>
}
使用此邏輯,為了更改按鈕,您必須更改 device.available,而您的上面的代碼沒有。 為此,我會推薦 2 個解決方案:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.