本文介绍了根据 redux 和路由器中的 jobId 获取特定的作业详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有不同工作 ID 的工作列表.我必须根据作业 ID 获取特定的作业详细信息.我为此创建了 action 和 reducer 函数.但是,我是 redux 的新手,无法理解如何将其与组件连接并显示结果.

我通过 axios 调用 api 以获取特定 ID 的作业详细信息.我不知道如何调用组件.现在,我得到了未定义的 jobId.

action.js

export const retrieveLocations = (jobId) =>(调度) =>{axios.get(retrieveUrl+'/jobs/'+jobId).then(res => {派遣({类型:检索位置,有效载荷:res.data.jobs.basicDetails});});};

减速器代码:

case 'RETRIEVE_LOCATION':返回{...状态,conLocations:action.payload}

组件代码:

从'react'导入React;从 'react-dom' 导入 ReactDOM;从'react-redux'导入{连接};从'react-router-dom'导入{withRouter};从../../stores/store"导入商店;从../../actions/locationActions"导入 {removeLocation,retrieveLocations};从../../actions/locationActions"导入 {removeAllLocation}让 _labels;类 ConfiguredLocation 扩展了 React.Component{构造函数(道具){超级(道具);this.handleRemove = this.handleRemove.bind(this);this.clearall = this.clearall.bind(this);}处理删除(mruCode){this.props.removeLocation(mruCode)}清除所有(){this.props.removeAllLocation()}componentDidUpdate(prevProps){让 currJobId = this.props.match.params.jobId;让 prevJobId = prevProps.match.params.jobId;if(currJobId!==prevJobId){this.props.retrieveLocations(jobId);}}componentDidMount(){让 {jobId} = this.props.match.params;this.props.retrieveLocations(jobId);console.log(this.props);}使成为(){const _labels = store.getLabels();const {conLocations} = this.props;返回(<div className="col-padding"><div className="pos-div"><h3>配置位置</h3><button className="allLargeBtn" onClick={()=>{this.clearall()}}>全部删除位置</button></div><hr/><table className="table">{conLocations.map((loct,index)=><tr key={index}><td><h5>{loct.mruCode} - {_labels[loct.division]} - {loct.country}</h5></td><td className="text-right"><img alt="DeleteIcon" onClick={()=>this.handleRemove(loct.mruCode)}className="deleteIconStyle" src="img/delete_large_active.png"/></td></tr>)}</tbody>

);}}const mapStateToProps = 状态 =>{返回 {conLocations:state.locationRed.conLocations};};const mapDispatchToProps = (调度) =>{返回{removeLocation: (mruCode)=>{dispatch(removeLocation(mruCode))},removeAllLocation: () =>{dispatch(removeAllLocation())},retrieveLocations:(jobId) =>{dispatch(retrieveLocations(jobId))}};};导出默认连接(mapStateToProps,mapDispatchToProps)(withRouter(ConfiguredLocation));

路线代码:

从'react'导入React;从 'react-dom' 导入 ReactDOM;从'react-router-dom'导入{Router、Route、IndexRoute、hashHistory};import { Security, ImplicitCallback, SecureRoute } from 'something...';从'../history'导入历史;从../stores/store"导入商店;从'../components/location/ConfiguredLocation'导入ConfiguredLocation;/*自定义组件导入*/从 './views/AppFrame' 导入 AppFrame;从 '../env-to-local' 导入 {something...};class AppNavigator 扩展了 React.Component {构造函数(道具){超级(道具);this.state = {加载:真实};}componentDidMount() {var self = this;setTimeout(() => {self.setState({ loading: false });}, 1000);}使成为() {如果(this.state.loading){返回 (<div className="fix"><i className="fa fa-2x fa-circle fa-spin"></i><div>加载</div>

)} 别的 {返回 (<路由器历史={历史}><div><安全发行人={soething...}client_id={某事...}redirect_uri={window.location.origin + '/app/callback'}scope={['profile', 'openid']}><Route path='/callback' component={ImplicitCallback}/><AppFrame/></安全><路由精确路径="/app/jobs/:jobId" component={ConfiguredLocation}/>

</路由器>);}}};module.exports = AppNavigator;

商店代码:

<AppNavigator/></提供者>

在控制台中检查时,我得到了这个空数组和这个.

请给我建议.如何根据 id 显示来自 api 的作业

解决方案

如果你想用 redux 调用 axios 这样的异步函数,你应该使用像 redux-sagaredux- 这样的中间件thunk 等等.

我会给你一些使用redux-thunk

的例子

制作商店

从'redux-thunk'导入thunkMiddleware;import { createStore, applyMiddleware } from 'redux';从<你的rootReducer路径>导入rootReducerconst createStoreWithMiddleware = applyMiddleware(thunk 中间件)(创建商店);const store = createStoreWithMiddleware(rootReducer);

action.js

export const retrieveLocations = (jobId) =>(调度) =>{axios.get(urlLoc+'/jobs/'+jobId).then(res => {派遣({类型:检索位置,有效载荷:res.data.job.locations});});};

i have list of jobs for different job id. i have to fetch the particular job details based on job id. I have created action and reducer function for that. But, i am new to redux not able to understand how to connect this with component and display the result.

i am calling the api by axios to get the job details on particular id. I am not aware of how to make the call into the component. Now, I am getting undefined jobId.

action.js

export const retrieveLocations = (jobId) => (dispatch) => {
  axios.get(retrieveUrl+'/jobs/'+jobId).then(res => {
      dispatch({
          type: RETRIEVE_LOCATION,
          payload: res.data.jobs.basicDetails
      });
  });
};

reducer code:

case 'RETRIEVE_LOCATION':
            return{
                ...state,
                conLocations:action.payload
            }

component code:

import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import {withRouter} from 'react-router-dom';
import store from '../../stores/store';
import {removeLocation,retrieveLocations} from '../../actions/locationActions';
import {removeAllLocation} from '../../actions/locationActions'

let _labels;

class ConfiguredLocation extends React.Component{
    constructor(props){
        super(props);

        this.handleRemove = this.handleRemove.bind(this);
        this.clearall = this.clearall.bind(this);
    }


    handleRemove(mruCode){
       this.props.removeLocation(mruCode)
    }

    clearall (){
      this.props.removeAllLocation()
    }
    componentDidUpdate(prevProps){
        let currJobId = this.props.match.params.jobId;
        let prevJobId = prevProps.match.params.jobId;
        if(currJobId!==prevJobId){
            this.props.retrieveLocations(jobId);
        }
    }
    componentDidMount(){
        let {jobId} = this.props.match.params;
        this.props.retrieveLocations(jobId);
        console.log(this.props);
    }

    render(){
        const _labels = store.getLabels();
        const {conLocations} = this.props;
        return(
            <div className="col-padding">
              <div className="pos-div"><h3>Configured Location</h3><button className="allLargeBtn" onClick={()=>{this.clearall()}}>Remove all location</button></div><hr/>
               <table className="table">
                    <tbody>
                        {conLocations.map((loct,index)=><tr key={index}>
                           <td><h5>{loct.mruCode} - {_labels[loct.division]} - {loct.country}</h5></td>
                           <td className="text-right"><img alt="DeleteIcon" onClick={()=>this.handleRemove(loct.mruCode)}className="deleteIconStyle" src="img/delete_large_active.png" /></td>
                        </tr>
                        )}
                    </tbody>
               </table>
            </div>
        );
    }

}

const mapStateToProps = state =>{
    return {
        conLocations: state.locationRed.conLocations
    };
  };

  const mapDispatchToProps = (dispatch) =>{
      return{
          removeLocation: (mruCode)=>{dispatch(removeLocation(mruCode))},
          removeAllLocation: () =>{dispatch(removeAllLocation())},
          retrieveLocations:(jobId) =>{dispatch(retrieveLocations(jobId))}
      };
  };


export default connect(mapStateToProps,mapDispatchToProps)(withRouter(ConfiguredLocation));

Route code:

import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, IndexRoute, hashHistory} from 'react-router-dom';
import { Security, ImplicitCallback, SecureRoute } from 'something...';
import history from '../history';
import store from '../stores/store';
import ConfiguredLocation from '../components/location/ConfiguredLocation';

/*Custom components imported */
import AppFrame from './views/AppFrame';

import {something...} from '../env-to-local';

class AppNavigator extends React.Component {

    constructor( props ) {
        super( props );
        this.state = {
            loading: true
        };
    }

    componentDidMount() {
        var self = this;
        setTimeout(() => {
            self.setState({ loading: false });
        }, 1000);
    }

    render() {
        if (this.state.loading) {
            return (
                <div className="fix"><i className="fa fa-2x fa-circle fa-spin"></i>
                    <div>Loading</div>
                </div>
            )
        } else {
            return (                    
                <Router history={history}>
                   <div>
                    <Security issuer={soething...}
                        client_id={something...}
                        redirect_uri={window.location.origin + '/app/callback'}
                        scope={['profile', 'openid']}>
                        <Route path='/callback' component={ImplicitCallback} />
                        <AppFrame />
                    </Security>
                    <Route exact path="/app/jobs/:jobId" component={ConfiguredLocation}/>
                    </div>
                </Router>
            );
        }
    }
};

module.exports = AppNavigator;

store code:

<Provider store={createStoreWithMiddleware(reducers)}>
            <AppNavigator />
        </Provider>

While checking in console, i am getting this empty array and this.

Please suggest me on this. how to display jobs from api based on id

解决方案

If you want to asynchronous function like axios call with redux, you should use middleware like redux-saga or redux-thunk and so on.

I'll give you some example for using redux-thunk

make store

import thunkMiddleware from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import rootReducer from <your rootReducer path>

const createStoreWithMiddleware = applyMiddleware(
    thunkMiddleware
)(createStore);

const store = createStoreWithMiddleware(rootReducer);

action.js

export const retrieveLocations = (jobId) => (dispatch) => {
  axios.get(urlLoc+'/jobs/'+jobId).then(res => {
      dispatch({
          type: RETRIEVE_LOCATION,
          payload: res.data.job.locations
      });
  });
};

这篇关于根据 redux 和路由器中的 jobId 获取特定的作业详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 06:58