【发布时间】:2019-09-22 11:58:55
【问题描述】:
class A extends Component {
constructor(props) {
super(props);
this.state = {
fruitsDetailsList: [],
fruitCode: this.props.fruitCode,
};
}
showModal = () => {
this.setState({ show: true });
};
hideModal = () => {
this.setState({ show: false });
};
componentDidMount() {
const url = 'http://localhost:3000/getFruitslist';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
fruitCode: this.state.fruitCode,
}),
})
.then(res => {
if (res.ok) {
return res.json();
}
throw new Error(res.status);
})
.then(res => {
this.setState({
fruitsDetailsList: res.fruitDetailsList,
});
})
.catch(error => {});
}
render() {
const columns = [
{
Header: 'Sr.No',
id: "row",
maxWidth: 50,
Cell: (row) => {
return <div>{row.index + 1}</div>
}
},
{
Header: 'Actions',
id: 'FruitName',
accessor: d => (
<div>
<B/>
</div>
)
}
];
return (
<div>
<ReactTable
className="-striped -highlight"
columns={columns}
data={this.state.fruitsDetailsList}
defaultPageSize={10}
noDataText={'No Data available.'}
/>
<p></p>
</div>
);
}
Class B extends component{
constructor(props) {
super(props);
this.state = { modal: false };
this.toggle = this.toggle.bind(this);
}
toggle() {
this.setState({
modal: !this.state.modal
});
}
render() {
return (
<div>
<Button onClick={this.toggle}/>
<Modal isOpen={this.state.modal}>
<ModalHeader>Fruits list</ModalHeader>
<ModalBody>
<Formik
initialValues={{fruitName: ''}}
onSubmit={(fields, action) => {
action.setSubmitting(true);
const url = 'http://localhost:3000/getFruit';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
fruitName: fields.fruitName,
}),
})
.then(res => {
action.setSubmitting(false);
console.log("Success!!!);
})
.catch(error => {});
}}
render={({ errors, touched, isSubmitting }) => (
!isSubmitting ? (
<Form>
<div className="form-group">
<label htmlFor="fruitName">FruitName</label>
<Field name="fruitName" type="text"/>
</div>
<div className="form-group">
<Button type="submit" className="bg-gradient-theme-left border-0 " size="m">Submit</Button>
</div>
</Form>
)
)}
/>
</ModalBody>
</Modal>
</div>
);
}
}
- 反应 JS
如您所见,有 2 个类
1)A组份
2)B组份
在组件 A 中,我将 B 组件称为 react-table 中的 Button
实际上,我们必须通过调用我们在组件 A 的 componentDidMount 中调用的 post API 请求 '/getFruitslist' 来渲染带有数据库中所有数据的反应表,以便反应表中的数据正确填充到表中
现在,当我们单击组件 B 的按钮时,会插入一条记录 数据库,但在组件 A 的 ComponentDidMount 中调用 API,即 组件 B 的父级,单击 B 组件的按钮时,数据不会填充到反应表中。如何做到这一点?
【问题讨论】:
-
在组件
A中创建一个函数,它将在状态中添加fruitName。将该函数传递给组件B。当表单提交调用该函数并传递fruitName。随着父组件中的状态发生变化,它也会反映在表格中。
标签: reactjs