如何在reactJS中从子组件更新父组件的状态 A类扩展组件{ 建造师(道具){ 超级(道具); 此.state={ 水果明细表:[], 果码:这个。道具。果码, }; } showModal=()=>{ this.setState({show:true}); }; hideModal=()=>{ this.setState({show:false}); }; componentDidMount(){ 常量url=http://localhost:3000/getFruitslist'; 获取(url{ 方法:“POST”, 标题:{ “内容类型”:“应用程序/json”, }, 正文:JSON.stringify({ 果码:this.state.果码, }), }) 。然后(res=>{ 如果(res.ok){ 返回res.json(); } 抛出新错误(res.status); }) 。然后(res=>{ 这是我的国家({ 水果明细表:res.水果明细表, }); }) .catch(错误=>{}); } render(){ 常量列=[ { 标题:“Sr.No”, id:“行”, 最大宽度:50, 单元格:(行)=>{ 返回{row.index+1} } }, { 标题:“操作”, id:'水果名', 访问者:d=>( ) } ]; 返回(
); } 类扩展组件{ 建造师(道具){ 超级(道具); this.state={modal:false}; this.toggle=this.toggle.bind(this); } 切换(){ 这是我的国家({ 模态:!this.state.modal }); } render(){ 返回( 水果清单 { action.setSubmitting(真); 常量url=http://localhost:3000/getFruit'; 获取(url{ 方法:“POST”, 标题:{ “内容类型”:“应用程序/json”, }, 正文:JSON.stringify({ 水果名:fields.fruitName, }), }) 。然后(res=>{ 动作。设置提交(错误); console.log(“成功!!!); }) .catch(错误=>{}); }} render={({错误,触摸,isSubmitting})=>( 提交( 果名 提交 ) )} /> ); } } -REACT JS 如您所见,有两个类 1) A部分 2) 成分B如何在reactJS中从子组件更新父组件的状态 A类扩展组件{ 建造师(道具){ 超级(道具); 此.state={ 水果明细表:[], 果码:这个。道具。果码, }; } showModal=()=>{ this.setState({show:true}); }; hideModal=()=>{ this.setState({show:false}); }; componentDidMount(){ 常量url=http://localhost:3000/getFruitslist'; 获取(url{ 方法:“POST”, 标题:{ “内容类型”:“应用程序/json”, }, 正文:JSON.stringify({ 果码:this.state.果码, }), }) 。然后(res=>{ 如果(res.ok){ 返回res.json(); } 抛出新错误(res.status); }) 。然后(res=>{ 这是我的国家({ 水果明细表:res.水果明细表, }); }) .catch(错误=>{}); } render(){ 常量列=[ { 标题:“Sr.No”, id:“行”, 最大宽度:50, 单元格:(行)=>{ 返回{row.index+1} } }, { 标题:“操作”, id:'水果名', 访问者:d=>( ) } ]; 返回(,reactjs,Reactjs,); } 类扩展组件{ 建造师(道具){ 超级(道具); this.state={modal:false}; this.toggle=this.toggle.bind(this); } 切换(){ 这是我的国家({ 模态:!this.state.modal }); } render(){ 返回( 水果清单 { action.setSubmitting(真); 常量url=http://localhost:3000/getFruit'; 获取(url{ 方法:“POST”, 标题:{ “内容类型”
在组件A中,我调用B组件作为反应表中的按钮 实际上,我们必须通过调用组件A的componentDidMount中调用的post API请求“/getFruitslist”来呈现包含数据库中所有数据的react表,以便在表中正确填充react表中的数据 现在,当我们点击组件B的按钮时,会插入一条记录 数据库,但作为API在组件A的ComponentDidMount中调用
组件B的父级,单击组件B的按钮时,数据不会填充到反应表中。如何实现这一点?有多种方法可以实现您想要的。最简单的方法是通过
道具传递必要的对象和值。在复杂的情况下,我建议对应用程序使用redux
在状态管理方面,当您需要在多个组件中访问状态对象时,更容易保持状态一致
传递道具:
一旦有了两个组件,数据就可以从A
传递到B
。下面分享一个小示例,说明如何实现这一点:
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>
);
}
}
A类扩展组件{
建造师(道具){
超级(道具);
此.state={
水果明细表:[],
果码:这个。道具。果码,
};
}
渲染{
返回(
)
}
}
Redux选项:
那么什么是Redux
JavaScript应用程序的可预测状态容器
基本上,应用程序的状态对象将位于一个公共位置,如果需要使用redux
中的MapStateTrops
功能访问它,您可以将其与每个组件匹配。该链接详细说明了如何访问该对象。一旦需要修改任何元素,您可以使用mapDispatchToProps
来执行此操作因此,请查找链接以进行进一步设置
进一步了解有关设置的信息,请从此处开始:
摘要:
在您的场景中,由于API调用,可能会频繁更新状态对象,我建议使用第二个选项。第一次查看时可能会比较复杂,但值得一试,因为您不需要担心状态一致性,并且通过props
在修改后会自动更新数据任何物体
我希望这会有所帮助!React的原理是将状态管理到顶部组件中。子组件不应保留对其父组件的引用以更新父组件状态。
要实现此行为,父组件应通过其属性将回调传递给子组件,然后子组件可以通过调用匹配属性来调用此回调
在您的示例中,您可以将属性onAddFruit
传递给B
组件。当POST
调用成功时,您应该调用此函数
class A extends Component {
constructor(props) {
super(props);
this.state = {
fruitsDetailsList: [],
fruitCode: this.props.fruitCode,
};
}
render {
return (
<B dataFromA={this.state.fruitsDetailsList} />
)
}
}
在父组件A
中,您定义了一个函数,该函数将向状态变量fruitsDetailsList
.T添加一个结果
.then(fruit => {
action.setSubmitting(false);
console.log("Success!!!);
this.props.onAddFruit(fruit);
})
handleAddFruit = fruit => {
this.setState(prevState => ({
fruitsDetailsList: [...prevState.fruitsDetailsList, fruit]
});
};
<B onAddFruit={this.handleAddFruit}/>