问题演示
我正处于学习阶段,我正在尝试使用 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);
}
上面的代码可以工作并且加载我的数据,但正如我提到的,我不知道这样做是否可以并且不会造成 future 的问题?当然,我会做一些if/else
来检查address
是否有值,但为了简单起见,我这样写。
我将发布 Component、Action 和Reducer 的代码,以便更好地了解该功能
创建 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()
的 reducer
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);
TL;DR
我想在 componentDidMount()
中使用变量(来自状态)调用 axios 请求,但该变量不会立即加载,因此我无法调用该操作,因为该变量是空。
请您参考如下方法:
当您收到地址属性时,您可以使用 componentWillReceiveProps
启动请求:
componentWillReceiveProps(nextProps) {
if (!this.props.checkweb && nextProps.checkweb) {
this.props.loadProfile(nextProps.checkweb.address);
}
}
编辑:如果您能够使用异步函数( promise )获取地址
,您可以执行以下操作:
componentDidMount() {
getAsyncAddress().then((address) => {
this.props.loadProfile(address);
}
}