在我的 reducer 中,它返回我从 api 获得的一组对象。我在列表上执行了一个 console.log 并且我能够看到该数组,但是当我访问我的 react 类中的 reducer 时,它显示为一个空数组,为什么会这样? 在我的 react 文件中的 render() 函数中,它确实出于某种奇怪的原因打印,但我有一个函数,我试图使用来自 reducer 的数据渲染单独的 div,并且数组显示为空。
getList() {
let arr = [];
if(this.props.popular){
arr = this.props.popular.map(item => {
return (
<div key={item.id} className="movie">
<img
src={`https://image.tmdb.org/t/p/w300${item.poster_path}`}
//onClick={() => this.displayModal(item)}
/>
</div>)
})
}
// console.log(arr)
// this.props.updateCurrentShowList(arr);
return arr;
}
我使用下面的 mapstatetoprops 函数中的 this.props.popular。
import { FETCH_POPULAR, RESET_POPULAR } from "../Actions/types";
let initialList = [];
export default function(state = initialList, action){
switch(action.type){
case FETCH_POPULAR:
//return action.payload || false;
initialList = initialList.concat(...action.payload);
//console.log(initialList);
return initialList;
case RESET_POPULAR:
initialList = action.payload;
return initialList;
default:
return state;
}
}
这里打印了 initialList 并起作用,然后我将其返回。
这是我在其他文件中的 mapStateToProps 函数,我想在其中访问数组。我在我的一个 reducer 文件中使用了 combinereducers。
function mapStateToProps(state) {
return {
popular: state.popular
};
}
为什么当我在 render() 中执行时 this.props.popular 打印正确,但每当我在其他地方使用它时,它却不打印?
Action 函数
export const fetchPopular = (searchTypeFormat, page) => async (dispatch) => {
let url = `https://api.themoviedb.org/3/discover/${searchTypeFormat}?api_key=${APIKEY}&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=${page}`;
//console.log(url);
const res = await axios.get(url);
//console.log(res.data.results)
dispatch({type: FETCH_POPULAR, payload: res.data.results});
};
我的商店创建
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reducers from './Reducers/index';
import reduxThunk from 'redux-thunk';
const store = createStore(reducers, {}, applyMiddleware(reduxThunk));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));
我以这种方式组合了我的 reducer
import { combineReducers } from 'redux';
import authReducer from './authReducer';
import popularReducer from './popularReducer';
import genreListReducer from './genreListReducer';
import searchByGenreReducer from './searchByGenreReducer';
import { reducer as formReducer } from 'redux-form';
import modalReducer from './modalReducer';
import detailsReducer from './moreDetailReducer';
import userDisplayList from './userDisplayList';
export default combineReducers({
auth: authReducer,
form: formReducer,
popular: popularReducer,
genreList: genreListReducer,
searchByGenre: searchByGenreReducer,
modalData: modalReducer,
details: detailsReducer,
displayList: userDisplayList
})
整个组件
import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
import { connect } from 'react-redux';
import * as actions from '../Actions';
class SearchPopular extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
page: 1
}
this.getList = this.getList.bind(this);
}
componentWillMount() {
//console.log(this.props.match.params.format)
this.props.fetchPopular(this.props.match.params.format, this.state.page);
console.log(this.props.popular)
console.log(this.getList());
}
getList() {
let arr = [];
if(this.props.popular){
arr = this.props.popular.map(item => {
return (
<div key={item.id} className="movie">
<img
src={`https://image.tmdb.org/t/p/w300${item.poster_path}`}
//onClick={() => this.displayModal(item)}
/>
</div>)
})
}
//console.log(arr)
// this.props.updateCurrentShowList(arr);
return arr;
}
render() {
console.log(this.props.popular);
return (
<div>
</div>
);
}
}
function mapStateToProps(state) {
return {
popular: state.popular,
updatedList: state.displayList
};
}
export default withRouter(connect(mapStateToProps, actions)(SearchPopular));
最佳答案
您正在以错误的方式进行状态更新。您所做的是,它最初总是采用空数组,然后追加到其中。
case 'FETCH_POPULAR':
return [...state, ...action.payload];
在你的 reducer 中试试这个。
****到你的主要问题 您正在尝试获取 store.popular 但您没有 popular in store
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const configureStore = () => {
const store = createStore(
combineReducers({
popular: Your reducer here
}),
composeEnhancer(applyMiddleware(thunk))
);
return store;
}
**** 新更新
我认为这是函数失去 this 引用的问题。
这就是我们在构造函数中使用 this.getList.bind(this)
的原因
因此,当我们调用 this.getList
时,函数会获取 this 的引用并可以使用它。因此,当您直接从任何其他函数调用它时,请使用 this.getList.bind(this)
componentWillMount() {
//console.log(this.props.match.params.format)
this.props.fetchPopular(this.props.match.params.format, this.state.page);
console.log(this.props.popular)
console.log(this.getList.bind(this));
}
关于javascript - 为什么我的 reducer 在 react/redux 中返回一个空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51407888/