React-Redux:使用 table 中的按钮将获取的 API 数据从组件发送到动态路由组件

React-Redux: send a fetched API data from a component to a dynamic route component using a button inside a table

我正在使用 react-redux 构建一个应用程序并且有 3 个主要问题。在志愿者组件中,我从商店获取志愿者数据,然后通过将数据和列(作为常量导入)传递给 table 组件来显示它。

志愿者组件:

import React, {Component} from 'react';
import { connect } from 'react-redux';
import { requestVolunteerData } from '../actions';
import { volenteerColumns as columns } from '../utils/constants';
import '../container/App.css';
import Table from '../components/Table/Table';
import Loading from '../components/Loading/Loading';
import {Link} from 'react-router-dom';

const mapStateToProps = state => {
    return {
        entities: state.requestEntitiesReducer.entities,
        isPending: state.requestEntitiesReducer.isPending,
        error: state.requestEntitiesReducer.error
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onRequestEntities: () => dispatch(requestVolunteerData())
    }
}

class Volenteer extends Component{
    
    componentDidMount () {
        this.props.onRequestEntities();
    }   
      
    render () {
        const { entities, isPending} = this.props;
        return isPending ?
            <Loading />
             :
            (
                <div className='tc'>
                    <h1 className='f1'>רשימת מתנדבים</h1>
                    <Table data={ entities } columns={ columns }/>  
                </div>
            );  
    }   
}

export default connect(mapStateToProps, mapDispatchToProps)(Volenteer);

常量文件 - 包含 volenteerColumns :

 import {Link} from 'react-router-dom';
    // Types
    export const REQUEST_ENTITIES_PENDING = 'REQUEST_ENTITIES_PENDING';
    export const REQUEST_ENTITIES_SUCCES = 'REQUEST_ENTITIES_SUCCES';
    export const REQUEST_ENTITIES_FAILED = 'REQUEST_ENTITIES_FAILED';
    
// Columns

export const volenteerColumns = [{
    dataField: 'name',
    text: 'שם פרטי'
  }, {
    dataField: 'name',
    text: 'שם משפחה'
  }, {
    dataField: 'phone',
    text: 'עיר'
  },{
    dataField: 'yeshuv',
    text: 'כתובת'
  },{
    dataField: 'phone',
    text: 'מספר טלפון'
  },{
    dataField: 'area',
    text: 'איזור פעילות מועדף'
  },{
    dataField: 'occupation',
    text: 'תחום עיסוק'
  }, {
    dataField: 'alertDonationInArea',
    text: 'התראה על תרומה באיזור'
  }, {
    dataField: 'alertdonationNearBy',
    text: 'התראה על תרומה קרובה'
  }, {
    dataField: 'status',
    text: 'סטטוס'
  }, {
    dataField: 'bDate',
    text: 'תאריך יום הולדת'
  }, {
    dataField: "_id",
    text: "פעולות",
    formatter: (rowContent, row) => {
      return (    
        <Link to={`/volenteerRoute/${_id}`}>
          <button className='btn btn-outline-primary btn lg'>view</button>
        </Link>
      )
    }
}];

它看起来像这样:

我想要的只是当我点击查看按钮时,它会转到一条新路线:<Route path='/volenteerRoute/:id' component={VolenteerDetails} />

并将显示该特定志愿者的数据。 我的问题是:

  1. 现在我想尽可能地从外部文件导入 volenteer 列(出于可读性原因和短代码)这不是真正的常量...因为按钮应该指向动态路径, 那么如何通过单击查看按钮来更改我的路线呢? 我知道我写得不正确(如何使用格式化程序)- 通过在外部文件中找到的按钮传递志愿者 ID 的正确方法是什么?

  2. 将志愿者的状态传递给 <Route path='/volenteerRoute/:id' component={VolenteerDetails} /> 的正确方法是什么,是通过这样的 Link:

     <Link to ={{pathname: "/volenteerRoute/:id",
      state: { volenteerDetails:  
      this.state.volenteerDetails}}} >
    

或通过另一个 fetch API 调用的 redux 操作(首选)?如果是这样,我该如何获取这些数据?这些是我的行动:

//volunteer
export const requestVolunteerData = () => getData('http://localhost:8000/api/volunteer');
export const requestOneVolunteerData = () =>  getData('http://localhost:8000/api/volunteer/:id');

调用getData函数的:

import {
    REQUEST_ENTITIES_PENDING,
    REQUEST_ENTITIES_SUCCES,
    REQUEST_ENTITIES_FAILED
} from './constants';
 
export const getData = (url) => (dispatch) => {
    dispatch ( {type: REQUEST_ENTITIES_PENDING} );
    fetch(url)
        .then ( response => response.json() )
        .then( resp => dispatch({type: REQUEST_ENTITIES_SUCCES, payload: resp.data }) )
        .catch(error => dispatch({type: REQUEST_ENTITIES_FAILED, payload: error}) ) 
}

但是第二个动作当然不起作用,因为我不知道如何将 ID 从视图按钮传递到那个动作

  1. VolenteerDetails(应该显示特定志愿者详细信息的组件)如何获取数据?是道具吗?

        const VolenteerDetails = ({ props}) => {
             console.log(props);
             return (
               <div>
                 <h2>volenteer details </h2>
               </div>
           )
        }
    

抱歉这个问题太长了,感谢您的帮助!!

在里面添加这个 route.js:

<Route exact path='/volenteerRoute' component={Volenteer} />
<Route path='/volenteerRoute/:id' component={VolenteerDetails} />

Table 查看按钮:

<Link to={{pathname: `/volenteerRoute/${item.id}`}}>View</Link>

您可以使用 react-router useParams().

获取点击视图的 ID

VolenteerDetails.js:

const VolenteerDetails = ({ props }) => {
     let { id } = useParams();
     console.log(id);
     // with id you can fetch API or call action even read data from store
     ...
}

VolenteerDetails 采取行动:

export const requestOneVolunteerData = (id) =>  getData(`http://localhost:8000/api/volunteer/${id}`);

奖励: 为了获得使用 redux 和路由的最佳体验,我更喜欢使用 connected-react-router

谢谢!这非常有帮助!除了 Table 查看按钮,它应该是:

{
    dataField: "_id",
    text: "פעולות",
    formatter: (cell) => {
      return (    
        <Link to={`/volenteerRoute/${cell}`}>
          <button className='btn btn-outline-primary btn lg'>view</button>
        </Link>
      )
    }
}

因为数据字段的单元格:“_id”是保存志愿者 ID 的单元格,这里很有用 link: https://allenfang.github.io/react-bootstrap-table/advance.html

但没有你的回答我无法做到,所以再次感谢!!

我会按照您的建议探索 connected-react-router