[英]make axios request using variable with the state set in a previous request
[英]Make axios request with variable from the state in componentDidMount
我正處於學習階段,我正在嘗試使用react和redux構建一個項目。 我已經創建了動作,Reducer和組件,到目前為止,從我的API獲取數據非常好。 現在,我嘗試調用axios請求(存在於操作中),但URL中有一個變量,但該變量處於狀態。 基本上我想實現的是:
componentDidMount() {
//call action to load profile data
let address = this.props.checkweb.address;
this.props.loadProfile(address);
}
上面的代碼的問題在於,安裝組件時address
為空,並且在很短的時間后變為可用。 如果我使用setTimeout
,它可以工作,但是我不知道這是否是一個好方法。 此代碼有效 。
componentDidMount() {
//wait 1 sec and call action to load profile data
setTimeout(function() {
let address = this.props.checkweb.address;
this.props.loadProfile(address);
}, 1000);
}
上面的代碼可以正常工作,並且可以加載我的數據,但是正如我提到的,我不知道這樣做是否合適,並且不會造成未來的問題? 當然,我會做一些if/else
檢查address
是否有值,但是為了簡單起見,我這樣寫。
在其中創建loadProfile()
的操作部分
export const loadProfile = (address) => (dispatch) => {
dispatch({
type: 'PROFILE_REQUEST',
isLoading: true,
error: null
});
return axios.get('https://localhost:8088/api/weapons/'+address)
.then(response => {
dispatch({
type: 'PROFILE_SUCCESS',
isLoading: false,
data: response.data
});
})
.catch(err => {
dispatch({
type: 'PROFILE_FAILED',
isLoading: false,
error: err
});
console.error("Failure: ", err);
});
}
這里有loadProfile()
的化loadProfile()
let profileApiState = {
data: {},
isLoading: false,
error:null
}
const profileApi = (state = profileApiState, action) => {
switch (action.type) {
case 'PROFILE_REQUEST':
case 'PROFILE_FAILED':
return {
...state,
isLoading: action.status,
error: action.error
};
case 'PROFILE_SUCCESS':
return {
...state,
data: action.data,
isLoading: action.status,
error: null
};
default: return {
...state
}
}
}
export default profileApi;
這是我正在執行渲染的組件
class Inventory extends Component {
componentDidMount() {
//call action to load weapons
let address = this.props.checkweb.address;
this.props.loadProfile(address);
}
render() {
return (
<div>
Some profile data
{this.props.profile.data}
</div>
);
}
}
const mapStateToProps = (state) =>{
return {
checkweb: state.checkWeb,
profile: state.profileApi
};
};
export default connect (mapStateToProps, actionCreators)(Inventory);
我想在調用具有可變(從狀態)的愛可信請求componentDidMount()
但變量不加載立刻如此,因為變量為空,我不能打電話的動作。
收到地址道具時,可以使用componentWillReceiveProps
發起請求:
componentWillReceiveProps(nextProps) {
if (!this.props.checkweb && nextProps.checkweb) {
this.props.loadProfile(nextProps.checkweb.address);
}
}
編輯:如果您能夠使用異步功能(承諾)獲取address
,則可以執行以下操作:
componentDidMount() {
getAsyncAddress().then((address) => {
this.props.loadProfile(address);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.