如何在React 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;

詹姆斯·唐纳利

您的UserRow组件是所谓的功能组件,而您的Users组件是所谓的类组件如React的State和Lifecycle文档中所述,功能组件没有局部状态

如果您希望能够在UserRow组件内使用状态,则需要先将转换为类组件

如果要直接修改Users组件的状态,则需要将回调函数传递UserRow组件中,但这可能会带来一些意外的副作用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章