对反应和还原是全新的,无法弄清为什么我无法通过功能组件中的this.props访问状态。
商店
我创建了旋转的初始状态,并在创建后将其传递到我的商店中。
import { createStore } from "redux";
import rotateReducer from "../reducers/rotateReducer";
const initialState = { rotating: true }
const store = createStore(rotateReducer, initialState)
export default store;
减速器
用于更改旋转状态的功能。
export default (state,action) => {
if (action.type === "rotate") {
return { rotating: action.payload }
}
return state;
}
Index.js
在这里,我导入商店和提供者,并包装在商店中传递的App组件作为道具。
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')
);
App.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);
答案 0 :(得分:0)
您应该将道具作为参数:
function App(props) {
console.log(props)
return(/* .... */)
}
尝试此操作并检查控制台输出。 (this.props可以在类组件中工作,但我更喜欢使用功能组件)
我通常只添加我需要的状态部分:
function mapStateToProps(state) {
return {
rotating: state.rotating
}
}
然后:
function App({rotating, /* more variables */}) {
console.log(rotating)
return(/* .... */)
}