【发布时间】:2019-06-10 02:59:31
【问题描述】:
我是第一次开发 react 应用程序并了解 redux。问题我在 App.js 中定义了一个商店并使用 Provider bu 将其传递给应用程序,当我尝试将其访问到子组件时我的控制台中有一个 undefined 在使用 mapStateToProps 进行映射后。请问你能检查我的代码并告诉我做错了什么吗?
我在 reducers 文件夹中创建了 2 个 reducer,调用 index.js 和 testIt.js 之后,我在 index.js 中导入 testIt.js,其中有一个 combineReducers 来添加功能 reducer。在我为 App.js 导出它并使用 react-redux 的提供者提供商店之后。
App.js
import React, { Component } from 'react';
import {BrowserRouter , Route} from "react-router-dom";
import { Provider } from 'react-redux';
import Store from "./reducers/index";
import { TestIt } from "./components/TestIt";
import './App.css';
//console.log(Store.getState());
class App extends Component {
render() {
return (
<div className="App">
<Provider store={Store}>
<BrowserRouter>
<Route exact path="/login" component={TestIt} />
</BrowserRouter>
</Provider>
</div>
);
}
}
export default App;
reducers/index.js
import { combineReducers, createStore } from 'redux';
import notes from "./testIt";
const leadApp = combineReducers({
notes
})
export default createStore(leadApp);
reducers/testIt.js
test .js
const initialState = [
{text: "Write code!"}
];
export default function notes(state=initialState, action) {
switch (action.type) {
default:
return state;
}
}
最后是我的子组件 src/components/TestIt.js
import React, { Component } from 'react';
import {connect} from 'react-redux';
export class TestIt extends Component {
constructor(props){
super(props)
}
render() {
console.log(this.props.notes)
return (
<div>
<h2>Welcome to TestIt!</h2>
<hr />
<h3>Notes</h3>
<table>
<tbody>
{this.props.notes.map(note => (
<tr>
<td>{note.text}</td>
<td><button>edit</button></td>
<td><button>delete</button></td>
</tr>
))}
</tbody>
</table>
</div>
)
}
}
const mapStateToProps = (state) => {
return notes : state.notes
}
// const mapDispatchToProps = dispatch => {
// return {
// }
// }
export default connect(mapStateToProps)(TestIt);
我现在有 this.props.notes 给我 undefined 的减速器 testIt.j 。我怀疑商店里有东西我传递给 provider即使我使用 connect() 方法进行连接, 也不会到达子组件。我希望在我的子组件中访问 testIt.js 减速器。
真的需要帮助,我尝试阅读了很多文章和文档。
【问题讨论】:
标签: reactjs react-redux