如何使用React中的props动态设置子组件中的数据



我已经解决了这个问题中的一个问题,将函数作为参数传递

现在我正在向后端发送向数据库添加新记录的请求,我想在添加新记录后立即更新表,从后端获取所有项目。

这是我的父App.js类,它有两个组件,分别是MainPanelTableFooterPanel

function App() {
const [customers, setCustomers] = useState([]);

useEffect(() => {
const fetchPostList = async () => {
const response = await service.getCustomerList();
setCustomers(response.data);
};
fetchPostList()
}, []);
const refreshTableData = () => {
const fetchPostList = async () => {
const response = await service.getCustomerList();
setCustomers(response.data);
};
fetchPostList()
}
return (
<div className="App">
<h1>Customer List</h1>
<MainPanel param={customers}/>
<TableFooterPanel funcParam={refreshTableData}/>
</div>
);
}
export default App;

我将刷新功能传递给TableFooterPanel,它有一个添加新记录的按钮,当添加新记录时会触发此功能。这是TableFooterPanel

function TableFooterPanel(props) {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const addNewCustomer = (name, surname) => {
service.addCustomer(name, surname);
props.funcParam();
}
return (
<>
<Card className='buttonFooter'>
<Form className='buttonFooter'>
<input type="text" placeholder="First Name" defaultValue={firstName} onChange={e => setFirstName(e.target.value)}></input>
<input type="text" placeholder="Last Name" defaultValue={lastName} onChange={e => setLastName(e.target.value)}></input>
<Button onClick={() => addNewCustomer(firstName, lastName)}>Add</Button>
</Form>
</Card>
</>
);
}
export default TableFooterPanel;

我想刷新主面板:中的表数据

function MainPanel(props) {
const [customers, setCustomers] = useState([]);

const deleteCustomer = (id) => {
service.deleteCustomerById(id);
}
return (
<ReactBootStrap.Table striped bordered hover>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{props.param &&
props.param.map((item) => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.firstName}</td>
<td>{item.lastName}</td>
<td><Button onClick={() => deleteCustomer(item.id)} ><FontAwesomeIcon icon={faTrashRestore} /></Button></td>
</tr>   
))}
</tbody>
</ReactBootStrap.Table>
);
}

这里发生的情况是,当我添加一个新记录时,表数据不会动态变化,但如果我添加第二个数据,那么我会看到以前的数据和更新表,但仍然不会显示最后添加的数据。如何刷新数据并将最新数据发送到主面板

export default MainPanel;

您的问题是这个部分:

const addNewCustomer = (name, surname) => {
service.addCustomer(name, surname);
props.funcParam();
}

看起来您是在调用完addCustomer服务之前调用刷新函数(props.funcParam()((因为这是一个Promise(。这导致您的fetch在更新现有数据之前就开始提取现有数据。

您需要使函数异步,然后像这样await

const addNewCustomer = async (name, surname) => {
await service.addCustomer(name, surname);
props.funcParam();
}

现在,您的函数将等待service.addCustomer完成执行,然后再执行刷新函数。

假设service.addCustomer(name,姓氏(是一个异步调用,它将数据发布到服务器。然后,您需要将addNewCustomer方法放入异步并等待此调用的响应,一旦获得响应,您需要调用props.funcParam((从服务器获取最新数据。

最新更新