[英]Using two redux actions when clicking a button
Sounds like something simple enough, but redux is just so darn confusing. 听起来很简单,但redux只是让人感到困惑。
As it is now, I have a list of buttons created based off of a reducer object, and when I click one of them, I make a get request which return me an object, which I then render accordingly. 就像现在一样,我有一个基于reducer对象创建的按钮列表,当我单击其中一个时,我发出一个get请求,它返回一个对象,然后我相应地进行渲染。
What I would like to add is the name of the button clicked and use it as a title to what is created from the get request. 我想添加的是点击按钮的名称,并将其用作从get请求创建的内容的标题。
Here is my current code: 这是我目前的代码:
//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});
});
};
}
Edit: added the code in the actions.js file. 编辑:在actions.js文件中添加了代码。
Why not just add an extra argument to fetchLogs and then dispatch another action? 为什么不在fetchLogs中添加额外的参数然后再发送另一个动作呢?
<ListGroupItem
bsStyle="warning" key ={module.id}
onClick={()=>this.props.fetchLogs(module.url, module.name)}>
{module.name}
</ListGroupItem>
And hence: 因此:
//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});
});
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.