简体   繁体   中英

Call dispatch function for Redux from string variable

I have a component that gets reused for various reasons. From the component I am updating different parts of the store based on the url parameter. I am having an issue trying to call the dispatch function based on a passed string. Here is my import:

import {updateUnassignedListingLeads, updateAssignedListingLeads} from "../../actions";

And then my code to call the dispatch. If I put the updateAssignedListingLeads where storeName is it works. I have also checked that the url is correct coming in. It says it is not a function.

reloadFilteredListingLeads = () =>{

let curr = this
var url = this.removeParameter()
const parsed = queryString.parse(this.props.location.search);
let column = parsed.column
let order = parsed.order
let term = parsed.term
let filters = parsed.filters
let group = parsed.group


const vals = {
  column: column,
  order: order,
  filters: filters,
  term: term
};

let strip = url.replace("/", "");
const storeName = eval('update' + group.charAt(0).toUpperCase() + group.slice(1));

axios.post('/filtered-' + strip, vals, headers).then(response => {
  curr.props.dispatch(storeName(response.data))
});
}

This is the bottom of the file. I know it works without trying to use a string variable as the dispatch action. If I replace storeName with updateAssignedListingLeads then it works.

const mapStateToProps = (state) =>{
  return {
    app: state.app,
  }
}

export default withRouter(connect(mapStateToProps)(ListingCoordinatorDetail));

Any help would be greatly appreciated. Thanks!

您是否在应用程序中使用 connect API 将 redux state 与 react 连接起来?

Ok, so I had to import it differently and add it to the eval like this:

import * as Update from '../../actions';

const storeName = eval(Update['update' + group.charAt(0).toUpperCase() + group.slice(1)]);
If you want to make your function dynamic and want's to dispatch.

Then you need to create one action for that. 

which is return type and payload. 

How redux works is you return type and payload and reducer changes your state as per that.

Create one action which return type and payload and reducer for that.

So, you can map your storeName function and response in your redux store.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM