gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:26:54 25 4
gpt4 key购买 nike

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

现在,我有一个基于 reducer 对象创建的按钮列表,当我单击其中一个按钮时,我发出一个 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 添加一个额外的参数,然后分派(dispatch)另一个操作?

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

关于javascript - 单击按钮时使用两个 redux 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40072435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com