我一直在使用redux动作来获取这样的数据:
示例:
export const example = () => dispatch => {
dispatch({ type: "FETCH_EXAMPLE_DATA_LOADING" });
return axios.get('/admin').then(({ data: exampleData })) =>
dispatch({ type: "FETCH_EXAMPLE_DATA_SUCCESS", payload: exampleData })
.catch(err => dispatch({ type: "FETCH_EXAMPLE_DATA_FAILED", payload: err }))
}
和Reducer示例:
const INITIAL_STATE = {
exampleData: []
};
case "FETCH_EXAMPLE_DATA_LOADING":
return { ...state, loadingData: true };
case "FETCH_EXAMPLE_DATA_SUCCESS":
return {
...state, exampleData: action.payload, loadingData: false
}
case "FETCH_EXAMPLE_DATA_FAILED":
return {
...state,
fetchError: 'some nonsense about an error!',
loadingData: false
}
问题是当我以概率形式获取数据并想要使用componentDidMount()呈现数据时,我这样做:
handleFetchData() {
if(this.props.assets.fetchError) {
return (
<h1>{this.props.assets.fetchError}</h1>
);
} else if(this.props.assets.loadingMovies) {
return (
<div className="loading">
<h1>Loading...</h1>
</div>
);
} else {
return the data!
}
}
这似乎在第一次登录该页面时工作得很好,但是当我尝试从其他页面导航到该页面时,出现一个错误,提示它无法获取未定义的数据。
我还尝试了人们在stackoverflow中提出的其他建议,例如:
fetchMovieResults() {
const {assets} = this.props;
if (assets) {
if (assets.fetchResultsError) {
// if error
return (
<div className="loading">
<h1>{assets.fetchResultsError}</h1>
</div>
);
} else if (assets.SearchResult && assets.SearchResult.Search && assets.SearchResult.Search.length > 0) {
// if data and more than 0
return assets.SearchResult.Search.map(movie => (
<div className="latest-admin" key={movie.Title}>
<div className="poster" style={{backgroundImage: `url(${movie.Poster})`}}></div>
<button onClick={() => this.props.chooseMovie(movie.imdbID, this.props.formValues, this.props.history)}>Choose Movie</button>
</div>
));
}
}
// no error or data
// has to be loading
return (
<div className="loading">
<h1>Loading...</h1>
</div>
);
}
但这使数据永久挂起而不真正渲染!有什么建议么? :)