单击按钮时使用两个 redux 操作

Using two redux actions when clicking a button

听起来很简单,但 redux 实在是太令人困惑了。

就像现在一样,我有一个基于 reducer object 创建的按钮列表,当我单击其中一个按钮时,我会发出一个获取请求,return 我 object,然后我相应地进行渲染。

我想添加的是单击按钮的名称,并将其用作从 get 请求创建的内容的标题。

这是我当前的代码:

//containers/module-buttons.js
//where the buttons are creared and bound to an action
//fetchLogs(moduleUrl) is with the get request I am making
class ModuleButtons extends Component{
    createListItems(){
        return this.props.modules.map((module)=>{
            return (
                <ListGroupItem bsStyle="warning" key ={module.id}
                               onClick={()=>this.props.fetchLogs(module.url)}>
                                {module.name}</ListGroupItem>
            );
        });
    }

    render(){
        return (
            <ListGroup>
                {this.createListItems()}
            </ListGroup>
        );
    }
}

function mapStateToProps(state){
    return {
        modules: state.modules

    };
}

function matchDispatchToProps(dispatch){
    return bindActionCreators({fetchLogs: fetchLogs}, dispatch);
}

//containers/module-log.js
//whenever a button is clicked, the json object from the get request is rendered here
//what I want to do it in the <h3> tags put the name of the button previously clicked.
class ModuleLog extends Component{

    render(){
        if (!this.props.module){
            return <Panel><h5>Please select a module</h5></Panel>;
        }
        else{
            const renderData = Object.keys(this.props.module)
            .map((mainKey, key )=> <Log mainKey={mainKey}
                      innerObject={this.props.module[mainKey]} key={key} />);
            return (
                <div>
                    <h3>[insert module name here]</h3>
                    <ul>{renderData}</ul>
                </div>
            );
        }
    }
}

function mapStateToProps(state){
    return {
      module: state.moduleLog
    };
}

export default connect(mapStateToProps)(ModuleLog);

// actions/actions.js
export const moduleClicked = (module) =>{
    return {
        type: "MODULE_CLICKED",
        payload: module
    }
}

export function fetchLogs(moduleUrl){
    console.log(moduleUrl);
    const request = axios.get(moduleUrl);
    return (dispatch) => {
        request.then(({data}) =>{
            dispatch({type: 'FETCH_MODULES', payload: data});
        });
    };
}

编辑:在 actions.js 文件中添加了代码。

为什么不向 fetchLogs 添加一个额外的参数,然后分派另一个操作?

<ListGroupItem 
  bsStyle="warning" key ={module.id}
  onClick={()=>this.props.fetchLogs(module.url, module.name)}>
    {module.name}
</ListGroupItem>

因此:

//actions.js

export function fetchLogs(moduleUrl, moduleName){
    console.log(moduleUrl);
    const request = axios.get(moduleUrl);
    return (dispatch) => {
        request.then(({data}) =>{
            dispatch({type: 'FETCH_MODULES', payload: data});
            dispatch({type: 'MODULE_CLICKED', payload: moduleName});
        });
    };
}