我想在moviedb api中获取一组电影。基于api参数,api对象中只有10-12个元素,所以如果我控制记录返回的电影数据,我应该只在加载应用程序时看到具有那么多元素的对象。但相反,应用程序提出了无休止的请求,似乎是一个接一个请求连接一个空对象。为什么它只请求一次,即使我只调用了renderMovies()方法一次?
movie_list.js(容器)
class MovieList extends Component {
renderMovies() {
this.props.fetchMovies()
console.log(this.props.movies)
//console.log('hitting multiple times')
}
render() {
this.renderMovies()
return (
<div>Hello</div>
);
}
}
function mapStateToProps(state) {
return {
'movies': state.fetchMovies
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ 'fetchMovies': fetchMovies }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(MovieList);
行动创作者
import { FETCH_MOVIES } from '../actions/index';
export default function(state = [], action) {
switch (action.type) {
case FETCH_MOVIES:
return state.concat([action.payload.data])
}
return state;
}
减速指数
import { combineReducers } from 'redux';
import MovieReducer from './movie_reducer';
const rootReducer = combineReducers({
'fetchMovies': MovieReducer
});
export default rootReducer;
减速
import axios from 'axios';
export const FETCH_MOVIES = 'FETCH_MOVIES';
const API_KEY = '2458c1d252003392f870911dc14151e7';
const ROOT_API = `https://api.themoviedb.org/3/movie/now_playing?api_key=${API_KEY}`;
export function fetchMovies(){
const url = `${ROOT_API}&page=1`
const request = axios.get(url)
return {
'type': FETCH_MOVIES,
'payload': request
};
}
以下是控制台输出的示例
答案 0 :(得分:1)
您在渲染功能中获取数据。每当道具发生变化时都会调用渲染,因此你的应用会进行初始渲染,获取电影,这会改变状态,从而导致渲染...将你的fetch放入componentDidMount生命周期方法中以防止这种情况发生。
class MovieList extends Component {
componentDidMount() {
this.props.fetchMovies()
}
renderMovies() {
console.log(this.props.movies)
//console.log('hitting multiple times')
}
render() {
this.renderMovies()
return (
<div>Hello</div>
);
}
}
function mapStateToProps(state) {
return {
'movies': state.fetchMovies
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ 'fetchMovies': fetchMovies }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(MovieList);