在我的react/redux应用程序中单击按钮时发出一个简单的get请求

Making a simple get request when clicking a button in my react/redux application

本文关键字:一个 简单 请求 get redux react 我的 应用程序 按钮 单击      更新时间:2023-09-26

对不起,如果这个问题太广泛,我似乎找不到一个适合我正在做的事情或有意义的例子。

基本上,我的一个reducer是一个对象,它包含列表中每个按钮拥有的id,名称和url。每当我单击其中一个按钮时,我想对该url发出get请求,并以列表的形式返回它包含的任何数据。目前,应用程序所做的只是打印出我按下的按钮的id、名称和url。我该如何向url发出get请求并显示包含的内容呢?

下面是我当前的代码:

//example reducer of the button:
export default function(){
return [
{
    id: 0,
    name: button1,
    url: http://jsoncodeINeed.com/api
},
{
    id: 1,
    name: button2,
    url: http://otherJsoncodeINeed.com/api
}
   ];
}
//reducer that will take care of the action:
export default function(state=null, action){
switch(action.type){
    case 'MODULE_CLICKED':
        return action.payload;
        break;
}
return state;
}
 //actions
export const moduleClicked = (module) =>{
    return {
        type: "MODULE_CLICKED",
        payload: module
    }
}
//container for where I want to post the data in the button:
class ModuleLog extends Component{
    render(){
            return (
                <Panel
                    {this.props.module.name}{this.props.module.url}
                </Panel>
            );
}
function mapStateToProps(state){
    return {
      module: state.moduleLog
    };
}
export default connect(mapStateToProps)(ModuleLog);
//container for the button group:
class ModuleButtons extends Component{
    createListItems(){
        return this.props.modules.map((module)=>{
            return (
                <ListGroupItemkey ={module.id}
                    onClick={()=>this.props.moduleClicked(module)}>{module.name}</ListGroupItem>
            );
        });
    }
    render(){
        return (
            <ListGroup>
                {this.createListItems()}
            </ListGroup>
        );
    }
}
function mapStateToProps(state){
    return {
        modules: state.modules
    };
}
function matchDispatchToProps(dispatch){
    return bindActionCreators({moduleClicked: moduleClicked}, dispatch)
}
export default connect(mapStateToProps, matchDispatchToProps)(ModuleButtons);

我的存储在index.js文件中,我在其中简单地显示组件,这些组件简单地显示容器。

您应该阅读redux页面中的AsyncActions文档。从本质上讲,您希望从单击按钮时触发的操作发出请求。接收到响应后,使用接收到的数据触发第二个操作(类似于"SUCCESS_REQUEST")。然后,reducer将相应地更新存储,这将更新您的UI。