在行动之前过早地反应redux thunk和组件渲染

时间:2018-05-25 22:22:08

标签: reactjs react-redux

我正在向API发送请求,然后将响应保存到数组以供以后与thunk一起使用,但问题是我的组件在我的操作之前调用渲染函数太快,从而将响应从API保存到数组。

我得到的错误是"Consider adding an error boundary to your tree to customize error handling behavior"。我设置“isFetching”bool状态相应地为true / false每个动作但是如果我在渲染中放置条件if isFetching is true then return <p>loading</p>,则渲染函数似乎完全忽略。负责从API设置数据的操作正常工作并设置正确,但已经太晚了。

问题是如何延迟渲染组件,以便在渲染时我已将数据保存到阵列并准备好使用?

更新代码:

Action.js:

import axios from "axios";
export let startFetch = () => {
    return {
        type: "START_FETCH"
    }
}
export let endFetch = (array) => {
    return {
        type: "END_FETCH",
        array
    }
}
export let fetchApi = () => {
    let url = "http://127.0.0.1:5000/api/stats"
    return (dispatch) => {
        dispatch(startFetch())
        return axios.get(url).then(
            (response) => {
                dispatch(endFetch(response.data))
            },
            (err) => {
                console.log(err);
            }
        )
    }
}

Reducer.js:

export let fetchApiReducer = (state={isFetching : false, array : []},action) => {
    switch(action.type){
        case 'START_FETCH':
            return {
                isFetching : true
            }
        break;

        case 'END_FETCH':
            return{
                isFetching : false,
                array : action.array
            }
        break;
        default:   
            return state;
    }
}

Container.js:

import React, {Component} from "react";
import {connect} from "react-redux";
import {bindActionCreators} from 'redux';
import {fetchApi} from "../actions/adsActions"

class AdsList extends Component {

    componentWillMount() {
            this.props.fetchApi();
    }

    renderList(ad) {
        return (
            <a className="list-group-item list-group-item-action flex-column align-items-start">
                <div className="d-flex w-100 justify-content-between">
                  <h5 className="mb-1">{ad.text}</h5>
                  <small className="text-muted">{ad.date}</small>
                </div>
            </a>
        );
    }


    render() {
        if(this.props.isFetching == true) {
            return (<p>Loading</p>);
         } else if (this.props.isFetching == false && this.props.array.length >= 1) {
                return (
                <div>
             {this.props.array.map(this.renderList)}
            </div>
         );
    }
}


}
function mapStateToProps(state) {
    return {
        isFetching: state.isFetching,
        array: state.array
    };
}


function matchDispatchToProps(dispatch){
    return bindActionCreators({fetchApi: fetchApi}, dispatch);
}


export default connect(mapStateToProps, matchDispatchToProps)(AdsList);

非常感谢。

0 个答案:

没有答案