![](/img/trans.png)
[英]React / Redux: mapStateToProps not actually mapping state to props
[英]React redux mapStateToProps - cannot access state as props
非常新的反应和 redux 并且无法弄清楚为什么我无法通过功能组件中的 this.props 访问 state。
店铺
我创建了初始的 state 用于旋转,并在创建时将其传递到我的商店。
import { createStore } from "redux";
import rotateReducer from "../reducers/rotateReducer";
const initialState = { rotating: true }
const store = createStore(rotateReducer, initialState)
export default store;
减速器
Function 改变 state 的旋转。
export default (state,action) => {
if (action.type === "rotate") {
return { rotating: action.payload }
}
return state;
}
索引.js
这里我导入了 store 和 Provider,并将 store 中传入的 App 组件包装为 prop。
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider } from "react-redux";
import store from "./store/store";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
应用程序.js
我试图加载道具的主要组件,但不断收到“无法读取未定义的属性'道具'”
import React from 'react';
import logo from './logo.svg';
import './App.css';
import { connect } from "react-redux";
import { startAction } from "./actions/startAction";
import { stopAction } from "./actions/stopAction";
function App() {
return (
<div className="App">
<header className="App-header">
<img
src={logo}
className={
"App-logo" +
(this.props.rotating ? "":" App-logo-paused")
}
alt="logo"
onClick={
this.props.rotating ?
this.props.stopAction : this.props.startAction
}
/>
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
const mapStateToProps = state => ({
...state
});
const mapDispatchToProps = dispatch => {
return {
startAction: () => dispatch(startAction),
stopAction: () => dispatch(stopAction)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
您应该将道具作为参数:
function App(props) {
console.log(props)
return(/* .... */)
}
试试这个并检查控制台 output。 (this.props 可以在 class 组件中使用,但我更喜欢使用 function 组件)
我通常只添加我需要的 state 的部分:
function mapStateToProps(state) {
return {
rotating: state.rotating
}
}
接着:
function App({rotating, /* more variables */}) {
console.log(rotating)
return(/* .... */)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.