【发布时间】:2020-03-06 08:17:42
【问题描述】:
我正在尝试将 React 与 Redux 一起用于前端部分,并在后端使用 django rest 框架。由于商店中的问题,在 App 组件的 Provider 标记中出现问题 getState。当我尝试在 Words.js 中使用 map 函数时,出现未定义使用 map 的错误。我相信这是因为数组的值为空。因此修复了getState的这个错误。 当未定义减速器时,即使在 App 组件的 Provider 中包含商店也会出现此错误。
当我加载一个静态数组时,它会在特定组件中正确呈现。
这是文件名中的 Redux Store:store.js
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import rootReducer from './reducers'
const initialState = {};
const middleware = [thunk];
const enhancer = composeWithDevTools(applyMiddleware(...middleware));
const store = createStore(
rootReducer,
initialState,
enhancer
);
export default store;
index.js 文件在下面
import App from './components/App'
import ReactDOM from 'react-dom';
import React from 'react';
ReactDOM.render(<App />, document.getElementById("app"));
他们使用 django rest_framework 操作类型文件 types.js 来创建数据。
export const GET_WORDS = "GET_WORDS";
操作文件 words.js
import { GET_WORDS } from "./types";
import axios from 'axios';
export const getWords = () => dispatch => {
axios.get('/api/words/')
.then(res => {
dispatch({
type: GET_WORDS,
payload: res.data
});
}).catch(err => console.log(err));
}
组合reducer文件
import { combineReducers } from "redux";
import words from './words';
export default combineReducers({
words
});
reducer 文件 word.js
import { GET_WORDS } from '../actions/types';[enter image description here][1]
const initialState = {
words: []
}
export default function (state = initialState, action) {
switch (action.type) {
case GET_WORDS:
return {
...state,
words: action.payload
}
default:
return state;
}
}
将在其中调用单词列表的组件:Words.js
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getWords } from "../../../actions/words";
export class Words extends Component {
static propTypes = {
words: PropTypes.array.isRequired,
getWords: PropTypes.func.isRequired
};
componentDidMount() {
this.props.getWords();
}
render() {
return (
<Fragment>
Hi
</Fragment>
)
}
}
const mapStateToProps = state => ({
words: state.words.words
});
export default connect(mapStateToProps, { getWords })(Words);
最后是 App 组件
import React, { Component, Fragment } from 'react';
import Footer from './Layout/Footer/Footer';
import Header from './Layout/Header/Header';
import WordsDashboard from './Content/Words/WordsDashboard';
import { store } from '../store';
import { Provider } from "react-redux";
import { Words } from './Content/Words/Words';
export class App extends Component {
render() {
return (
<Provider store={store}>
<Fragment>
<Header />
React Buddy
<Words />
<Footer />
</Fragment>
</Provider>
)
}
}
export default App;
【问题讨论】:
标签: reactjs redux django-rest-framework react-redux