首页 > 解决方案 > 根据从下拉列表 reactjs -redux 中选择的位置获取货币值

问题描述

我有一个位置下拉列表。在我的实现中,我必须根据下拉列表中的位置变化来显示货币。我的数据如下: [{mruCode: "1700", country: "US", countryText: "United States", Division: "WORLDWIDE_INDUSTRIAL",currency:"USD"}....]。如果我选择美国,它将显示美元作为标签。到目前为止我已经做到了。

动作(加载数据):

export const loadData = () => {
  return (dispatch) => {
    return axios.get(serviceUrl)
    .then(response=>{
      dispatch(getLocationData(response.data.mruPreferences))
    })
    .catch(error=>{
      throw(error);
    });
  };
};

export const currencyLists = mruCode =>({
  type: CURRENCY_LIST,
  payload: mruCode
});

减速器(加载数据)

case 'GET_DATA_SUCC':
           return{
               ...state,
               location:action.location
           }

case 'CURRENCY_LIST':
        let newState = Object.assign({}, state)
        let newCurrList = newState.location.filter((el) => el.mruCode === action.payload)
        return Object.assign({}, newState, {
            currList: newCurrList
        });

组件代码:

class LocationList extends React.Component{
    constructor(props){
        super(props);
        this.state={
            isLoading:false,
        };

        this.handleChange = this.handleChange.bind(this);
    }

    componentDidMount() {
      this.props.loadData();
    }

    handleChange(){
      this.props.currencyLists(mruCode);
    }

    render(){
      const{location}=this.props;
      console.log(this.props.currList);
      const _labels = store.getLabels();
        return(<div>
            <span className="btnElement_spacing">You are viewing pricing for </span> 
             <select id="toggleLocationName">
                                  {location.map(item =>
                   <option  key={item.id}  value={item} onClick={()=>this.handleChange(item.mruCode)}>{_labels[item.division]}</option>
                    )}
          </select> 
          <span className="btnElement_spacing"> in </span>
                  {this.props.currList.map((item,index)=><label id="toggle-currency" key ={index}>{item.currency}</label>)}
            </div>
             );
    }
}

const mapStateToProps = state => {
    return {
      location: state.locationRed.location,
      currList: state.locationRed.currList
    }
  }

  const mapDispatchToProps = dispatch => {
    return {
      loadData:()=>{dispatch(loadData())},
      currencyLists:(mruCode)=>{dispatch(currencyLists(mruCode))}
      }
    }


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

现在,我得到了空的 currList。如何从选定的下拉列表中获取货币

标签: javascriptreactjsredux

解决方案


reduxlocation状态是对象(映射键值)还是数组?因为如果它是一个对象,你不能使用 find 方法,但你应该像这样使用它:

case 'CURRENCY_LIST':
        let cList = state.location[action.id]
          return{
              ...state,
              currList: cList
          };

推荐阅读