一个新的反应。我想在下面的代码中更新用户的状态。我知道这不是更新记录的正确方法,任何人都可以帮助我,这是更新记录的最佳方法。预先感谢。
在这里,我想在用户更改状态时更改其状态。
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;
答案 0 :(得分:3)
您的UserRow
组件是所谓的功能组件,而您的Users
组件是所谓的类组件。功能组件没有本地状态,如React的State and Lifecycle documentation中所述。
如果您希望能够在UserRow
组件中使用状态,则需要首先convert it to a class component。
如果您想直接修改Users
组件的状态,则想将pass a callback function through放入您的UserRow
组件中,但这可能会有一些意想不到的副作用。 / p>