使用Redux来使用函数和钩子时,我很难转换基于类的组件。 我要
无法读取未定义的属性“ props”
这是我的实际代码:
import React from 'react';
import { connect } from 'react-redux';
function App() {
const { newValue } = this.props;
return (
<div className="App" style={{ paddingTop: '10px' }}>
<input type="text" />
<button>Click me!</button>
<h1>{newValue}</h1>
</div>
);
}
const mapStateToProps = store => ({
newValue: store.clickState.newValue
});
export default connect(mapStateToProps)(App);
如果我将function App()
更改为class App extends Component
并将我的const { newValue } = this.props;
放入render()
方法中,它就可以正常工作。但是只有function App()
我仍然犯错。
答案 0 :(得分:2)
功能组件将props作为常规参数。
?
function App(props) {
const { newValue } = props;
return (
<div className="App" style={{ paddingTop: '10px' }}>
<input type="text" />
<button>Click me!</button>
<h1>{newValue}</h1>
</div>
);
}
或者更好的是,通常您会破坏道具以让用户知道props
的形状。
function App({newValue}) {
...
}
意思是,组件的用户将知道(仅通过查看函数声明)组件将接受哪些道具。
答案 1 :(得分:1)
您正在尝试在道具的功能组件中使用this
。
const { newValue } = this.props;
应该是
function App(props) {
const { newValue } = props;