我遇到了一个无限循环,它不断从API中获取信息。
如果将fetchTheMovie()包裹在if语句中,但我不理解原因,任何想法或任何更好的解决方案,则可以解决此问题?
if (!movie.Title) {
fetchTheMovie(id);
}
端点是/ movie / id
电影组件:
const SingleMovie = (props) => {
const { id } = useParams();
const {movie} = props;
useEffect(() => {
const {fetchTheMovie} = props;
fetchTheMovie(id);
}, []);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(WithSpinner(SingleMovie));
WithSpinner组件:
const WithSpinner = (WrappedComponent) => {
const Spinner = ({ isLoading, ...otherProps }) => {
return isLoading ? (
<SpinnerOverlay>
<SpinnerContainer />
</SpinnerOverlay>
) : (
<WrappedComponent {...otherProps} />
);
};
return Spinner;
};
使用组件的页面
const Page = ({ loading }) => {
const { id } = useParams();
return (
<div>
<SingleMovieComp isLoading={loading} />
</div>
);
};
行动:
export function fetchMovieStart() {
return {
type: SingleMovieActionTypes.FETCH_MOVIE_START,
};
}
export function fetchMovieSuccess(movie) {
return {
type: SingleMovieActionTypes.FETCH_MOVIE_SUCCESS,
payload: movie,
};
}
export function fetchMovieError(error) {
return {
type: SingleMovieActionTypes.FETCH_MOVIE_ERROR,
payload: error,
};
}
export const fetchMovieAsync = (movieId) => {
return (dispatch) => {
dispatch(fetchMovieStart());
fetch(`URL`)
.then((response) => response.json())
.then((movie) => dispatch(fetchMovieSuccess(movie)))
.catch((error) => dispatch(fetchMovieError(error.message)));
};
};
减速器:
const INITIAL_STATE = {
loading: false,
movie: {},
};
const singleMovieReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case SingleMovieActionTypes.FETCH_MOVIE_START: {
return {
...state,
movie: {},
loading: true,
};
}
case SingleMovieActionTypes.FETCH_MOVIE_SUCCESS: {
return {
...state,
movie: action.payload,
loading: false,
};
}
case SingleMovieActionTypes.FETCH_MOVIE_ERROR: {
return {
...state,
loading: false,
};
}
default:
return state;
}
};
您可以尝试以下操作:
const ComponentWithSpinner = WithSpinner(SingleMovie);
//create single movie container
const SingleMovieContainer = (props) => {
const { id } = useParams();
const { fetchTheMovie } = props;
//remove the useEffect from SingleMovie
useEffect(() => {
fetchTheMovie(id);
//you need to add these dependencies
}, [fetchTheMovie, id]);
//Here you could try to use useSelector to get the movie
// and pass to SingleMovie but I think you already do
// that somewhere else
//return component with spinner so SingleMovieContainer
// will not unmount when you load movie
return <ComponentWithSpinner {...props} />;
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(SingleMovieContainer);
问题在于,当您加载影片时,SingleMovie会被卸载,而当加载为false时会被加载,这会导致加载设置为true(调度了fetchMovie),因此会再次将其卸载。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句