gpt4 book ai didi

javascript - 存储来自 reducer props 的数据

转载 作者:行者123 更新时间:2023-12-01 02:54:40 24 4
gpt4 key购买 nike

我在 actions 中有一个函数可以调用 api。操作的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);
})
}
}

我在像这样的Reducers中使用相同的函数-

reducer 的index.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
})

导出默认数据;

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

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);

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

console.log(this.props.resultCame)

然后结果出现,这意味着 api 被正确调用,但我想将结果存储在状态变量中。因此在调用 loadData()< 后在 componentDidMount(),我正在 querylist 中设置状态。

但是 this.state.querylist 为空,这意味着数据尚未设置。

如何正确设置数据?

最佳答案

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

关于javascript - 存储来自 reducer props 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46784747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com