【问题标题】:Why if I does not handle the result from fetch api correctly, then fetch goes into error. using redux-thunk为什么如果我没有正确处理 fetch api 的结果,那么 fetch 就会出错。使用 redux-thunk
【发布时间】:2017-06-07 13:22:15
【问题描述】:

我通过 fetch api 获取数据:[{name: "s"}]。获取操作进行得非常顺利。但是我没有在组件 App 中正确处理这一行 return <p key={index}>{item}</p> 中的数据。我知道我应该将 {item} 替换为 {item.name}。但是我不明白如果我以不正确的方式使用{item},为什么提取操作会出错?

这是我的代码。并且日志结果是[Object]-------error-----

import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware} from "redux";
import { Provider, connect } from 'react-redux';
import thunkMiddleware from 'redux-thunk';

const actions = {
    search: params => (dispatch) => {
        dispatch(actions.beginSearch());
        fetch("http://127.0.0.1:8000/search",{
            method: 'POST',
            data:  {},
            credentials: true,
        }).then((res) => {
            return res.json()
        }).then((res) => {
            console.log(res.data)//res.data = [{name: "s"}];
            dispatch(actions.doneSearch(res.data));
        }).catch(() => {
            console.log('-------error-----');
            // dispatch(actions.failSearch("error"));
        });
    },
    beginSearch: () => ({
        type: 'BEGIN_SEARCH',
    }),
    doneSearch: data => ({
        type: 'DONE_SEARCH',
        payload: data,
    }),
    failSearch: err => ({
        type: 'FAIL_SEARCH',
        payload: err,
    }),
}

class App extends React.Component {
    render() {
        const {dispatch, listdata} = this.props;
        return (
            <div>
                {
                    listdata.map((item,index) => {
                        return <p key={index}>{item}</p>
                    })
                }
                <button onClick={()=>{
                    dispatch(actions.search())
                }}>click to get data...</button>
            </div>
        );
    }
}
const mapStateToProps = (state) => {
    return {
        listdata: state,
    };
}

const Container = connect(mapStateToProps)(App);
const reducers = (state=[], action) => {
    switch (action.type) {
        case "DONE_SEARCH":
            return [...action.payload]
        default:
            return state;
    }

}
const store = createStore(reducers, applyMiddleware(thunkMiddleware) );

render(
    <Provider store={store}>
        <Container />
    </Provider>,
    document.getElementById('container'),
);

谢谢你的帮助~

【问题讨论】:

    标签: javascript reactjs redux react-redux redux-thunk


    【解决方案1】:

    由于您是在第二个then 中调度您的操作,所以当它最终在您的渲染函数中一直出错时,这就是错误冒泡的地方。然后下面的catch 抓住了它。

    请记住,当您有一个函数链时,错误会一直沿链向上冒泡,直到有东西抓住它或您的 UI 爆炸。

    【讨论】:

    • 感谢您的回答。但我不能很好地理解它。有什么标准文件提到这个吗?
    猜你喜欢
    • 2017-06-12
    • 2016-09-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2020-10-28
    相关资源
    最近更新 更多