存储减速器道具的数据

时间:2017-10-17 07:30:33

标签: javascript reactjs redux react-redux

我在动作中有一个函数可以进行api调用。 index.js of actions

0.5*T.mean(T.nnet.softplus(l_unl)) + 0.5*T.mean(T.nnet.softplus(l_gen))

我在Reducers中使用的相同功能 -

减压器的index.js

export const GET_QUERY_LIST='GET_QUERY_LIST';

export const loadData=()=>{
    return(dispatch)=>{
        axios({
            method:'GET',
            url:Constants.URLConst+"/Query,
            headers:Constants.headers
        }).then((response)=>{
            return dispatch({
                type:GET_QUERY_LIST,
                response
            });
        }).catch((e)=>{
            console.log(e);
        })
    }
}

导出默认数据;

我在我的js文件中使用这个reducer函数,比如home.js,如下所示

function getQueryData(state=[],action){
    switch(action.type){
        case GET_QUERY_LIST:
            return Object.assign({},state,{
                result_get_query:action.response
            })

        default:
                return state

    }
}

const data=combineReducers({
    getQueryData
})

我将数据存储在resultCame变量中。在渲染功能中,如果我这样做,

import React,{Component} from 'react';
import './App.css';
import {loadData} from './actions';
import {connect} from 'react-redux';
import Header from './Header.js';
// import './Home.css';

export class Home extends Component{
    constructor(props){
        super(props);
        this.state={
            querylist:[]
        }
        this.handleChange=this.handleChange.bind(this);
    }

    componentDidMount(){
        this.props.loadData();

    }

    handleChange(){
        this.setState({
            querylist:this.props.resultCame
        })
    }

    render(){
        console.log("home.js",this.state.querylist);
        //this.props.resultCame.resultMeta.data.ProfileData.UserId
        if(this.props.resultCame.resultMeta){
        return( 
            <div> 
                <Header/>

                    <div>{this.handleChange()}</div>

            </div>          
            )
        }else{
            return null;
        }   
    }

}

const mapStateToProps=(state)=>{
    return{
        resultCame:state.getQueryData
    }
}

export default connect(mapStateToProps,{
    loadData:loadData
})(Home);

然后结果来了,这意味着api被正确调用,但是我想将结果存储在一个状态变量中。在调用console.log(this.props.resultCame) componentDidMount()中,我设置了状态loadData()

querylist为空,这意味着数据未设置。

如何正确设置数据?

2 个答案:

答案 0 :(得分:1)

您正在使用异步工作的axios。这意味着它在执行任何操作之前等待响应从API到达。当您使用ComponentDidMount()并调用操作然后立即致电setState时,this.state.queryset为空的可能原因是因为它是在axios收到来自API调用的任何内容之前分配的。收到setState的回复后,您必须axios,而不仅仅是运行它。

答案 1 :(得分:1)

您应该使用 ComponentWillReceiveProps(nextProps)来更新状态,因为axios成功通话的回复将出现在更新的下一个道具中,因为您将收到它们作为发送时的redux商店 输入:GET_QUERY_LIST,有效负载。

相关问题