Javascript 将道具设置为子组件中的状态
在这里,我想将道具设置为子组件中的状态。 我有一个充满ajax请求的表。顺便说一句,我正在使用库。 我的表格上有一个编辑按钮,可以打开一个包含表单的模式 父组件Javascript 将道具设置为子组件中的状态,javascript,reactjs,Javascript,Reactjs,在这里,我想将道具设置为子组件中的状态。 我有一个充满ajax请求的表。顺便说一句,我正在使用库。 我的表格上有一个编辑按钮,可以打开一个包含表单的模式 父组件 import React, {Component} from 'react'; import axios from 'axios'; import API from '../../Helpers/Api' import {Table, Divider, Tag, message, Popconfirm, Icon} from 'an
import React, {Component} from 'react';
import axios from 'axios';
import API from '../../Helpers/Api'
import {Table, Divider, Tag, message, Popconfirm, Icon} from 'antd';
import {
Card,
CardBody,
CardHeader,
Col,
Row
} from 'reactstrap';
import EditCountry from './EditCountry'
var token = JSON.parse(localStorage.getItem("token"));
let config = {
headers: {
Authorization: token,
Accept: 'application/json'
}
}
class ListCountry extends Component {
constructor(props) {
super(props);
this.columns = [
{
title: 'نام کشور',
dataIndex: 'name',
key: 'name',
// render: text => <a href="javascript:;">{text}</a>,
},
{
title: 'وضعیت',
dataIndex: 'isForeign',
key: 'isForeign',
render: isForeign => (
<div>
<Tag color={isForeign ? 'blue' : 'purple'}>
{isForeign ? 'کشور خارجی است' : 'کشور خارجی نیست'}
</Tag>
</div>
),
},
{
title: '',
dataIndex: '',
key: 'x',
render: (text, record) =>
this.state.countries.length >= 1 ? (
<span>
<a onClick={() => this.handleEdit(record.key)}>ویرایش کشور</a>
<Divider type="vertical" />
<Popconfirm
icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
title="آیا از حذف این کشور مطمئن هستید؟"
onConfirm={() => this.handleDelete(record.key)}
okText="حذف"
cancelText="لغو"
>
<a>حذف کشور</a>
</Popconfirm>
</span>
) : null,
},
];
this.state = {
countries: [],
openModal: false,
rowId:''
}
}
getCountries = e => {
var self = this;
axios.get( API + '/country',
config
)
.then(function (response) {
const results= response.data.map(row => ({
key: row._id, // I added this line
name: row.name,
isForeign: row.isForeign,
Id: row._id,
}))
self.setState({ countries : results });
})
.catch(function (error) {
console.log(error);
});
};
componentDidMount() {
this.getCountries();
}
handleDelete = id => {
var self = this;
axios.delete( API + `/country/${id}`,
config
)
.then(function (response) {
const countries = [...self.state.countries];
self.setState({ countries: countries.filter(item => item.key !== id) });
message.success('عملیات حذف با موفقیت انجام شد.')
})
.catch(function (error) {
console.log(error);
});
}
handleEdit = id => {
this.setState({
rowId: id,
openModal: !this.state.openModal
})
}
render() {
return (
<div className="animated fadeIn">
<Row className="justify-content-center">
<Col xs="12" md="12">
<Card>
<CardHeader>
<strong>لیست کشورها</strong>
</CardHeader>
<CardBody>
<Table className="rtl text-right" columns={this.columns} dataSource={this.state.countries}/>
<EditCountry open={ this.state.openModal } handleEdit= {this.handleEdit} rowId={ this.state.rowId } />
</CardBody>
</Card>
</Col>
</Row>
</div>
)
}
}
class EditCountry extends Component {
constructor(props) {
super(props);
this.state = {
id : this.props.rowId
};
}
handleCancel = () => {
this.props.handleEdit();
};
render() {
return (
<div>
<Modal
title="Basic Modal"
>
// form
</Modal>
</div>
);
}
}
import React,{Component}来自'React';
从“axios”导入axios;
从“../../Helpers/API”导入API
从“antd”导入{表、分隔符、标记、消息、Popconfirm、图标};
进口{
卡片
名片夹,
万向节,
上校,
一行
}来自“反应带”;
从“/EditCountry”导入EditCountry
var token=JSON.parse(localStorage.getItem(“token”);
让配置={
标题:{
授权:令牌,
接受:'application/json'
}
}
类ListCountry扩展组件{
建造师(道具){
超级(道具);
此值为。列=[
{
标题:نامکشو',
数据索引:“名称”,
关键字:“名称”,
//呈现:text=>,
},
{
标题:“وضعیت”,
数据索引:“isForeign”,
关键字:“isForeign”,
呈现:isForeign=>(
{是外国的吗?'
),
},
{
标题:“”,
数据索引:“”,
键:“x”,
呈现:(文本、记录)=>
this.state.countries.length>=1(
这个.handleEdit(record.key)}>
this.handleDelete(record.key)}
okText=“حذف”
cancelText=“لغو”
>
حذف کشور
):null,
},
];
此.state={
国家:[],
OpenModel:错误,
rowId:“”
}
}
getCountries=e=>{
var self=这个;
axios.get(API+/country),
配置
)
.然后(功能(响应){
const results=response.data.map(行=>({
key:row.\u id,//我添加了这一行
名称:row.name,
isForeign:row.isForeign,
Id:row.\U Id,
}))
self.setState({国家:结果});
})
.catch(函数(错误){
console.log(错误);
});
};
componentDidMount(){
这个。getCountries();
}
handleDelete=id=>{
var self=这个;
delete(API+`/country/${id}`,
配置
)
.然后(功能(响应){
const countries=[…self.state.countries];
self.setState({countries:countries.filter(item=>item.key!==id)});
信息、成功(信息、成功)
})
.catch(函数(错误){
console.log(错误);
});
}
handleEdit=id=>{
这是我的国家({
罗维德:是的,
OpenModel:!this.state.openModel
})
}
render(){
返回(
)
}
}
出口国
子组件
import React, {Component} from 'react';
import axios from 'axios';
import API from '../../Helpers/Api'
import {Table, Divider, Tag, message, Popconfirm, Icon} from 'antd';
import {
Card,
CardBody,
CardHeader,
Col,
Row
} from 'reactstrap';
import EditCountry from './EditCountry'
var token = JSON.parse(localStorage.getItem("token"));
let config = {
headers: {
Authorization: token,
Accept: 'application/json'
}
}
class ListCountry extends Component {
constructor(props) {
super(props);
this.columns = [
{
title: 'نام کشور',
dataIndex: 'name',
key: 'name',
// render: text => <a href="javascript:;">{text}</a>,
},
{
title: 'وضعیت',
dataIndex: 'isForeign',
key: 'isForeign',
render: isForeign => (
<div>
<Tag color={isForeign ? 'blue' : 'purple'}>
{isForeign ? 'کشور خارجی است' : 'کشور خارجی نیست'}
</Tag>
</div>
),
},
{
title: '',
dataIndex: '',
key: 'x',
render: (text, record) =>
this.state.countries.length >= 1 ? (
<span>
<a onClick={() => this.handleEdit(record.key)}>ویرایش کشور</a>
<Divider type="vertical" />
<Popconfirm
icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
title="آیا از حذف این کشور مطمئن هستید؟"
onConfirm={() => this.handleDelete(record.key)}
okText="حذف"
cancelText="لغو"
>
<a>حذف کشور</a>
</Popconfirm>
</span>
) : null,
},
];
this.state = {
countries: [],
openModal: false,
rowId:''
}
}
getCountries = e => {
var self = this;
axios.get( API + '/country',
config
)
.then(function (response) {
const results= response.data.map(row => ({
key: row._id, // I added this line
name: row.name,
isForeign: row.isForeign,
Id: row._id,
}))
self.setState({ countries : results });
})
.catch(function (error) {
console.log(error);
});
};
componentDidMount() {
this.getCountries();
}
handleDelete = id => {
var self = this;
axios.delete( API + `/country/${id}`,
config
)
.then(function (response) {
const countries = [...self.state.countries];
self.setState({ countries: countries.filter(item => item.key !== id) });
message.success('عملیات حذف با موفقیت انجام شد.')
})
.catch(function (error) {
console.log(error);
});
}
handleEdit = id => {
this.setState({
rowId: id,
openModal: !this.state.openModal
})
}
render() {
return (
<div className="animated fadeIn">
<Row className="justify-content-center">
<Col xs="12" md="12">
<Card>
<CardHeader>
<strong>لیست کشورها</strong>
</CardHeader>
<CardBody>
<Table className="rtl text-right" columns={this.columns} dataSource={this.state.countries}/>
<EditCountry open={ this.state.openModal } handleEdit= {this.handleEdit} rowId={ this.state.rowId } />
</CardBody>
</Card>
</Col>
</Row>
</div>
)
}
}
class EditCountry extends Component {
constructor(props) {
super(props);
this.state = {
id : this.props.rowId
};
}
handleCancel = () => {
this.props.handleEdit();
};
render() {
return (
<div>
<Modal
title="Basic Modal"
>
// form
</Modal>
</div>
);
}
}
类EditCountry扩展组件{
建造师(道具){
超级(道具);
此.state={
id:this.props.rowId
};
}
handleCancel=()=>{
this.props.handleEdit();
};
render(){
返回(
//形式
);
}
}
正如你看到的,我正在将道具设置为状态,但是id
是空的,我是否遗漏了什么?
提前感谢您的rowID流程如下:
this.props.handleEdit(myID); or this.props.handleEdit(this.state.id);
this.props.handleEdit()代码>
this.props.handleEdit
。这将在父级中设置未定义的rowId
必须在代码中的某个位置设置rowId,例如在子组件中,如下所示:
this.props.handleEdit(myID); or this.props.handleEdit(this.state.id);
这将设置id,并且rowID将定义为传递给handleEdit的任何内容
但这不会更新子组件中处于您的状态的id,因为父状态更新后将不会再次调用构造函数
要更新子状态,必须使用componentDidUpdate侦听rowId更改,或者直接从父组件使用this.props.rowId
componentDidUpdate(prevProps) {
if (this.props.rowId!== prevProps.rowId) {
this.setState({id: this.props.rowId});
}
}
希望这能有所帮助。您能向我们展示保存rowId的父组件吗?是的,当然,更新了我的问题发布了整个组件。在您的子组件中,改用props.rowId。运气不好,它是空的,因为一开始rowId是空的,但在ajax请求之后,我已经设置为rowiid,有没有生命周期方法会在调用子组件之后立即触发?调用get是什么意思?有componentDidMount和componentDidUpdate。当我点击表上的编辑按钮时,我将设置rowId并显示模式,也许我可以在之后将rowId道具设置为子状态。是的,您可以使用setState从模式更新id。然后必须将其传递给this.props.handleEdit函数。这将更新父rowId状态。这是我的问题。我想在我的子组件中将rowId设置为state,但我不能这样做。