reactjs - 如何在反应js中更新状态
问题描述
我是新来的反应。我想在下面的代码中更新用户的状态。我知道这不是更新记录的正确方法谁能帮助我,这是更新记录的最佳方法。提前致谢。
在这里,我想在用户更改状态时更改用户的状态。
import React, { Component } from 'react';
import { Badge, Card, CardBody, CardHeader, Col, Row, Table } from 'reactstrap';
import axios from '../../global/config'
import { AppSwitch } from '@coreui/react';
function UserRow(props) {
const user = props.user
const userStatus = user.status ? "Active" : "Inactive";
function ChnageUserStatus(){
axios.delete('..some api end point..'+props.user._id,{
data: { "status": !user.status }
})
.then(response => {
console.log(response.data);
//.. something is missing here
})
.catch(function (error) {
console.log(error);
})
}
return (
<tr key={user.id}>
<td>{userStatus}</td>
<td><AppSwitch id="status" name="status" checked={user.status ? true : false} className={'mx-1'} variant={'pill'} color={'primary'} onChange={ChnageUserStatus} /> </td>
</tr>
)
}
class Users extends Component {
state = {
usersInfo: []
}
componentDidMount() {
axios.get('...api end point here...')
.then(response => {
const users = response.data.data;
this.setState( { usersInfo: users } );
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<div className="animated fadeIn">
<Table responsive hover>
<thead>
<tr>
<th scope="col">Status</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{this.state.usersInfo.map((user2, index) =>
<UserRow key={index} user={user2} />
)}
</tbody>
</Table>
</div>
)
}
}
export default Users;
解决方案
Your UserRow
component is what's known as a functional component whereas your Users
component is what's known as a class component. Functional components do not have a local state, as described within React's State and Lifecycle documentation.
If you want to be able to make use of state within your UserRow
component, you'll need to convert it to a class component first.
If you want to directly modify the state of the Users
component, you'll instead want to pass a callback function through into your UserRow
component, but this may have some unexpected side effects.
推荐阅读
- amazon-web-services - NextJS 使用 ISR 部署到 AWS Amplify - 构建时间太长
- debugging - 如何使用 GDB 中的“维护信息符号表”打印的结果?
- python - Python在元组列表中找到浮点最近的值
- r - R使用变量重命名excel表
- python - AttributeError:模块'keras.utils'没有数据生成器的属性'Sequence'
- flutter - Flutter 2.5.0,将父类转换为子类失败(在 1.22.6 中可以)
- eclipse - 移动 .config 文件夹
- java - 尝试在空对象引用 MediaStore 上调用虚拟方法“int java.lang.String.lastIndexOf(int)”
- java - 如何在android studio中删除android虚拟设备发布版本?
- postgresql - postgressql 插入日期函数