繁体   English   中英

React - Redux:使用 Thunk 进行异步调用

[英]React - Redux : async call with Thunk

我正在学习使用 react-redux,特别是我会通过调用 API 来检索信息。

我目前以这种方式构建了我的项目:

/src
  /Components
   MeetingInformation.js
  /Redux
   actions.js
   reducers.js
   store.js
 App.js

在我的action.js

export const meetingInformation = (meeting) => {
    return(dispatch) => {
        fetch('apiLinkToTheMeeting')
        .then(res => res.json())
        .then(meeting => {
            dispatch({
                type: 'MEETING_INFORMATION',
                meeting: meeting
            })
        })
    }
}

减速器.js

const initialState = {
    meeting: []
}

export const meetingReducer = (state = initialState, action) => {
    switch(action.type){
        case 'MEETING_INFORMATION':
            return [...state, ...action.meeting]
    }
    return state;
}

export default meetingReducer;

store.js

import { createStore, compose, applyMiddleware } from "redux";
import { meetingReducer } from './reducers';
import thunk from 'redux-thunk';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export const store = createStore(
    meetingReducer, 
    composeEnhancers(
        applyMiddleware(
            thunk
        )
    )
);

会议信息.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { meetingInformation } from '../Redux/actions';

class MeetingInformation extends Component {
    constructor(props){
        super(props);
        this.state = {
            meetingMotivation: '',
            start: ''
        }
    }
componentDidMount(){
    this.props.meetingInformation()
}
handleSubmit = (e) => {
    e.preventDefault();
    this.props.meetingInformation(this.state)
}

render(){
    console.log(this.props)
    return(
        <div>

        </div>
    )
}}
const mapDdispatchToProps = (dispatch) => {
    return {
        meetingInformation: (meeting) => dispatch(meetingInformation(meeting))
    }
}
export default connect(null, mapDdispatchToProps)(MeetingInformation)

现在我不知道我所做的是否正确,但是 MeetingInformation 的 console.log 是空的,而且我的操作也有错误:

会议信息似乎为空

{meetingInformation: ƒ}
meetingInformation: meeting => {…}
arguments: (...)
caller: (...)
length: 1
name: "meetingInformation"
__proto__: ƒ ()
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Promise.then (async)        
(anonymous) @   actions.js:6

编辑:

响应的日志是:

Response {type: "basic", url: "myapiurl", redirected: false, status: 200, ok: true, …}
type: "basic"
url: "myapiurl"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers
__proto__: Headers
body: (...)
bodyUsed: false
__proto__: Response

我应该做的是使用 thunk 从我的数据库中恢复信息。 我能怎么做?

太感谢了。

几件事情要注意。

  • 您正在记录this.props 在这个阶段,你的 props 有方法meetingInformation 您将需要 map redux state 到您的道具。
const mapStateToProps = state => {
    return {
        meeting: state,
    }
};
  • 在您的减速器中,您正在传播 state 即return [...state, action.meeting] 即使您当前的问题得到解决,您的减速器仍然会有问题。 所以传播 state.meeting 即[...state.meeting, action.meeting]
  • 您收到的错误取决于您的 api 返回的数据结构。 您已打印响应,但body中的内容被隐藏。 所以打印并分析响应的正文。

我已经使用您的代码并在本地使用示例 API 对其进行了测试,并且它可以工作。

在此处查看工作演示。 分析我的代码并对您的代码进行必要的更改,看看它是如何进行的。 任何进一步的问题都会提供正确的 api 响应日志,这将有助于调试。

https://codesandbox.io/s/nifty-black-fh8rd?file=/src/components/MeetingInformation.js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM