reactjs - 获取响应数据后 React JS & Axios Render

标签 reactjs axios

我怎样才能让我的组件在从 axios 获取数据后呈现获取请求?
我有以下组件:

class CardPool extends React.Component{
    constructor(props){
        super(props);

        this.state = {
            cardListBacklog: [],
        };
    }

    componentWillMount(){
        axios.get('/cards').then(function(response){
            this.setState({cardListBacklog: response.data});
        }.bind(this));
    }

    render(){

        return(
            <div class="row">
                <Section name="Construction of Component 1 with a huge ass name that wont really fit in the section">
                    <Column columnName="BACKLOG">
                        <CardList id="card-list-1" column="0" cardList={this.state.cardListBacklog}/>
                    </Column>
                </Section>
            </div>
        );
    }
}


class CardList extends React.Component{
    constructor(props){
        super(props);

        this.state = {
            cardList: [],
            laneID: this.props.column
        }
    }

    componentWillMount(){
        this.setState({
            cardList: this.props.cardList,
        });
    }
render(){
        const {connectDropTarget} = this.props;

        return connectDropTarget(
            <div class={"card-list " + this.addClass()} id={this.props.id}>
                {   
                    this.state.cardList ?
                        this.state.cardList.map((card) => {
                            return <Card key={card.id} state={card} laneID={this.state.laneID}/>
                        })
                        : null
                }
            </div>
        );
}

问题在于statecardListBacklog传递给 CardList未更新,cardListCardList组件保持为空。我究竟做错了什么?难道是因为我设置了state使用 props 的属性?

最佳答案

你没有给 CardPool 的机会通过 axios 在响应到达时重新渲染的组件称呼。

修改render CardPool 的功能组件如下:

return this.state.cardListBacklog.length
        ? <div class="row">
            <Section name="Construction of Component 1 with a huge ass name that wont really fit in the section">
                <Column columnName="BACKLOG">
                    <CardList id="card-list-1" column="0" cardList={this.state.cardListBacklog}/>
                </Column>
            </Section>
          </div>
        : null;

This demo演示准系统实现

关于reactjs - 获取响应数据后 React JS & Axios Render,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48099811/

相关文章:

ajax - 使用 Axios 将某些 XHR 请求优先于其他请求

javascript - axios.get 请求返回 GET,HEAD 作为响应

javascript - 在vue中使用环境变量

javascript - 我可以在 react-native 中使用 reactJS 库吗?

javascript - react 良好的 uploader 不绑定(bind)到表单

javascript - 我如何在 React 中重用一个方法来处理多个不同的引用?

reactjs - 在 next.js 中带有 css 模块的 tailwind css

reactjs - 如何在 React 中对输入进行 Base64 编码?

node.js - 有没有办法限制我从响应中获取的数据量?

javascript - 在自定义 View 中调用 super() 时,确保传递与传递组件的构造函数相同的 Prop