我想知道在生命周期中应该从哪里获取数据。我试图将数据放入componentDidMount()
,componenWillMount()
但未成功...
componentWillMount(){
// this fetch the data from back-end set a store state with the payload
this.props.fetchUser();
this.setState({userData:this.props.auth});
}
//fetchMethod
export const fetchUser = () => async dispatch =>{//using redux-thunk
const res= await axios.get('/api/current_user')
dispatch({type:FETCH_USER, payload:res.data});
};
Run Code Online (Sandbox Code Playgroud)
在我的渲染函数中,我尝试通过调用使用提取的userData this.state.userData
。但这是不确定的。我也尝试通过调用正确的存储状态来获得它,也没有成功。根据我的本地存储,我没有得到的是定义了存储状态。希望有人能告诉我我做错了什么。谢谢!
您可以在componentWillMount或componentDidMount生命周期方法中进行提取(需要注意的是,当您使用服务器呈现的应用程序时,如果在componentWillMount中发出请求,则会遇到同步服务器呈现的html和重新水化的html的问题。)
未定义this.state.userData的原因是因为对数据的调用本质上是异步的。我建议向您的组件添加功能,以检查是否正在进行api调用(isLoading
也许是?),以及是否已完成(isLoaded
也许?)。
在实现方面,假设您使用connect
react-redux
更高阶的组件,它将像这样:
class YourComponent extends React.Component {
componentDidMount() {
this.props.fetchUser();
}
render() {
const { isLoading, isLoaded, data } = this.props;
if (isLoading) return <Loader />; // Or whatever you want to return when it is loading
if (!isLoaded || !data) return null; // If it is not loading and its not loaded, then return nothing.
return (
<div>
<h1>{data.name}</h1>
<h2>{data.id}</h2>
</div>
)
}
}
const mapStateToProps = state => ({
isLoading: state.user.isLoading,
isLoaded: state.user.isLoaded,
userData: state.user.data
});
export default connect(mapStateToProps, { fetchUser })(YourComponent);
Run Code Online (Sandbox Code Playgroud)
在动作分派器/中间件中,您将需要考虑异步调用的开始。假设这是由于redux thunk造成的...
const initialState = {
isLoaded: false,
isLoading: false,
data: {},
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_USER:
return {
...state,
isLoading: true,
}
case FETCH_USER_SUCCESS:
return {
isLoading: false,
isLoaded: true,
data: action.payload
};
default:
return state;
}
};
export default reducer;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6846 次 |
最近记录: |