Вложенные маршруты не повторно отображают ParentComponent после функции обновления и удаления? - PullRequest
0 голосов
/ 30 марта 2020

Я имею с Re-render с родительским функциональным компонентом. Мои функции обновления и удаления обрабатываются в Redux, после успешного выполнения не выполняется повторная визуализация родительского функционального компонента

***This my Main component where i am getting clients from Api USing Redux it is working working
import React, { Fragment,useEffect } from 'react'
import {connect} from 'react-redux';
import {getClients,deleteClient} from '../Redux//actions/clientActions';
import {Spin,Table,Tag,Button} from 'antd';
import { Link } from 'react-router-dom';
import Moment from 'react-moment'

const Clients =({getClients,deleteClient,client:{clients,loading},history})=> {

    useEffect(()=>{
        getClients()
    }
    ,[getClients]);


    const columns = [
        {
          title:'Company',
          dataIndex: 'companyName',
          key: 'companyName',
          render: text => <a>{text}</a>,
        },
        {
          title: 'Type',
          dataIndex: 'type',
          key: 'type',
        },
        {
          title: 'Price Type',
          dataIndex: 'typePrice',
          key: 'typePrice',
        },
        {
            title: 'Partita Iva',
            dataIndex: 'partitaIva',
            key: 'partitaIva',
          },
          {
            title: 'Codice Fiscale',
            dataIndex: 'codiceFiscale',
            key: 'codiceFiscale',
          },
          {
            title: 'Name',
            dataIndex: 'name',
            key: '1',
          },
          {
            title: 'SurName',
            dataIndex: 'surname',
            key: '2',
          },
          {
            title: 'Address',
            dataIndex: 'address',
            key: '3',
          },
          {
            title: 'City',
            dataIndex: 'city',
            key: '3',
          },
          {
            title: 'Zip',
            dataIndex: 'zip',
            key: '4',
          },
          {
            title: 'Country',
            dataIndex: 'country',
            key: '5',
          },
          {
            title: 'Phone',
            dataIndex: 'phone',
            key: '6',
          },
          {
            title: 'Email',
            dataIndex: 'email',
            key: '7',
          },
        {
          title: 'Domains',
          key: 'domains',
          dataIndex: 'domains',
          render: domains => (
            <span>
              {domains&&domains.map(domain => {
                let color = domain.length > 5 ? 'geekblue' : 'green';
                return (
                  <Tag color={color} key={domain}>
                    {domain.toUpperCase()}
                  </Tag>
                );
              })}
            </span>
          ),
        },
        {
          title: 'Notes',
          dataIndex: 'notes',
          key: 'notes',    
        },
        {
            title: 'Creator Id',
            dataIndex: 'createdByID',
            key: 'createdByID',    
          },
          {
            title: 'Date',
            dataIndex: 'date',
            key: 'date',
            render:(text)=>(
              <>
              <Moment format='YYYY/MM/DD'>{text}</Moment>
              </>
            ) 
          },
          {
            title: '',
            render:(record)=>(
              <> 
              <Button style={{
                marginBottom:"5px"
              }} type="primary" ghost>
              <Link to={`/clients/update/${record._id}`}>Update</Link>
              </Button>
           <Button type="primary" style={{
                marginBottom:"5px"
              }}  ghost>
             <Link to={`/clients/${record._id}`}>Detail</Link>
           </Button>
          </>
            )
          },


      ];

        return loading && clients.length === 0 ? (
          <div style={{
            position:"absolute",
            left:"50%",
            top:"50%",
            traverse: 'translate(-50%, -50%)'
          }}>
             <Spin/>
          </div>
           ):
            (
                <Fragment>
                    <Table pagination={{ defaultPageSize: 4, pageSizeOptions: ['10', '20', '30']}} columns={columns} dataSource={clients}  scroll={{ x: 1300 }}/>
                </Fragment>
            )



}

const mapStateToProps = state =>{
   return {

     client:state.client

    }
  }



export default connect(mapStateToProps,{getClients,deleteClient})(Clients);

***. Это моя страница сведений, и я реализую функцию удаления. Функция отлично выполняется и переходит на главную клиент, но клиенты не обновляются на главной странице после удаления


import React, { Fragment,useEffect,useState } from 'react'
import {connect} from 'react-redux';
import {withRouter,useParams,useHistory,Redirect} from 'react-router-dom';
import {getClient,deleteClient} from '../Redux/actions/clientActions'
import { Card,Spin,Button,Modal } from 'antd';
const gridStyle = {
    width: '33%',
    textAlign: 'center',
  };

const ClientDetail =({client:{client},getClient,deleteClient,loading,history})=> {
   let [visible,setVisible] = useState(false)
    let {id} = useParams()
    useEffect(()=>{
        getClient(id)
    },[getClient,id])


  const handleDelete=()=>{
    deleteClient(id)
   setVisible(true)
  }

  const handleOk = () => {
    setVisible(false)
    history.push('/clients')
  };





        return loading  && client === null? (
            <div style={{
                position:"absolute",
                left:"50%",
                top:"50%",
                traverse: 'translate(-50%, -50%)'
              }}>
                 <Spin/>
              </div>
        ): (
            <Fragment>
            <Modal
            title="Confirmation Dailog"
          visible={visible}
        //   onOk={handleOk}
          footer={[
            <Button key="back" onClick={handleOk}>
              OK
            </Button>,
          ]}
        >
           <p>Client Has been Deleted Successfully...</p>
        </Modal>
                  <Card style={{textAlign:"center",
                  marginTop:"2rem"
                  }} title="Client Detail">

    <Card.Grid style={gridStyle}>CompanyName: {client&&client.companyName}</Card.Grid>
    <Card.Grid  style={gridStyle}>Type:{client&&client.type}</Card.Grid>
    <Card.Grid style={gridStyle}>PriceType:{client&&client.typePrice}</Card.Grid>
    <Card.Grid style={gridStyle}>PartitaIva:{client&&client.partitaIva}</Card.Grid>
    <Card.Grid style={gridStyle}>CodiceFiscale:{client&&client.codiceFiscale}</Card.Grid>
    <Card.Grid style={gridStyle}>Name:{client&&client.name}</Card.Grid>
    <Card.Grid style={gridStyle}>SurName:{client&&client.surname}</Card.Grid>
    <Card.Grid style={gridStyle}>Address:{client&&client.address}</Card.Grid>
    <Card.Grid style={gridStyle}>City:{client&&client.city}</Card.Grid>
    <Card.Grid style={gridStyle}>Zip:{client&&client.zip}</Card.Grid>
    <Card.Grid style={gridStyle}>Country:{client&&client.country}</Card.Grid>
    <Card.Grid style={gridStyle}>Phone:{client&&client.phone}</Card.Grid>
    <Card.Grid style={gridStyle}>Email:{client&&client.email}</Card.Grid>
    <Card.Grid style={gridStyle}>Domains1:{client&&client.domains[0]}</Card.Grid>
    <Card.Grid style={gridStyle}>Domains2:{client&&client.domains[1]}</Card.Grid>
    <Card.Grid style={gridStyle}>Domains3:{client&&client.domains[2]}</Card.Grid>
    <Card.Grid style={gridStyle}>Notes:{client&&client.notes}</Card.Grid>
    <Card.Grid style={gridStyle}>CreatorID:{client&&client.createdByID}</Card.Grid>
    <Button type="danger" onClick={handleDelete} style={{ width: '40%',marginTop:"1rem",marginBottom:"1rem"}}>Delete</Button>
  </Card>
            </Fragment>
        )

}
const mapStateToProps=state=>({
    client:state.client
})
export default connect(mapStateToProps,{getClient,deleteClient}) (withRouter(ClientDetail));

1 Ответ

1 голос
/ 31 марта 2020

Вот пример с button and OnClick ниже, который вы можете использовать для своей рабочей логики c. Я надеюсь, что это поможет вам.

...
const ExampleComponent = props => {
    useEffect(()=>{
        getClients()
    }
    ,[getClients]);



    const handleDelete = () => {
      const {asyncDelete, id, history} = props;

      asyncDelete({id, onSuccess: () => {
          getClients();
          // or history.push('/');
        }
      });
    }


    return(
      <>
          ...
          <button onClick={handleDelete}
          ...
      </>
    )
}

const mapDispatchToProps = dispatch => ({
  asyncDelete: ({ id, onSuccess }) => dispatch(asyncDelete({ id, onSuccess }))
});

...

Предположим, reudx-thunk и топор ios в actions.js файле

...
export const asyncDelete = ({ id, onSuccess }) => {
  return dispatch => {
    ...
    axios
      .delete(`/user/${id}`)
      .then(response => {
              ...
              onSuccess();
       })
      .catch(error => console.log(error));
  };
};
...

Я передам onSuccess() метод к действию asyn c, когда удаление выполнено и если удаление выполнено правильно, этот метод также будет выполнен, и компонент будет обновлен снова. Вы можете также применить эту логику c к Вложенным маршрутам, хотя есть разные способы, которыми один из них может быть одной и той же логикой c.

...