听起来很简单,但redux只是让人感到困惑。
就像现在一样,我有一个基于reducer对象创建的按钮列表,当我单击其中一个时,我发出一个get请求,返回一个对象,然后我相应地进行渲染。
我想添加的是点击按钮的名称,并将其用作从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文件中添加了代码。
答案 0 :(得分:0)
为什么不在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});
});
};
}