1

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

志愿者组件:

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. 将 volenteer 的状态传递给 的正确方法是什么<Route path='/volenteerRoute/:id' component={VolenteerDetails} />,是通过这样的链接:

     <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>
           )
        }
    

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

4

2 回答 2

1

在里面添加这个route.js

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

表格视图按钮:

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

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

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

于 2021-01-13T08:40:42.597 回答
1

谢谢!这非常有帮助!除了表格视图按钮,它应该是:

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

因为 dataField 的单元格:“_id”是保存志愿者 id 的单元格,这里是一个有用的链接: https ://allenfang.github.io/react-bootstrap-table/advance.html

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

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

于 2021-01-13T19:44:28.867 回答