首页 > 解决方案 > 如何在反应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;

标签: reactjs

解决方案


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.


推荐阅读