我无法理解为什么我的props.updateBuilding无效.
当prop在render方法中时,以下工作
class Buildings extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.fetchBuildings();
}
renderBuildings(building) {
return (
<div>
<p> {building.name}</p>
</div>
);
}
render() {
return (
<div>
{this.props.buildings.map(this.renderBuildings)}
<button type="button" className="btn btn-success" onClick={this.props.updateBuilding.bind(this, 1)}>Edit</button>
</div>
);
}
}
function mapStateToProps(state) {
return { buildings: state.buildings.all };
}
function mapDispatchToProps(dispatch){
return bindActionCreators({ fetchBuildings, updateBuilding}, dispatch);
}
Run Code Online (Sandbox Code Playgroud)
但是当我this.props.updateBuilding
按照下面的方式添加renderBuildings方法时......
renderBuildings(building) {
return (
<div>
<p> {building.name}</p>
<button type="button" className="btn btn-success" onClick={this.props.updateBuilding.bind(this, building.id)}>Edit</button>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
Cannot read property 'props' of undefined
Run Code Online (Sandbox Code Playgroud)
updateBuildings
当它在renderBuildings方法中时,似乎无法读取prop ,我不确定是什么导致了这个.
spe*_*.sm 18
在我的情况下,我忘了添加props
作为构造函数的参数.
constructor(props) {
super(props);
}
Run Code Online (Sandbox Code Playgroud)
Phi*_*arg 17
你错过了这个错误.props
未定义,调用的props
是undefined,即this
关键字.您可以通过传入第二个参数来手动设置地图功能的上下文
this.props.buildings.map(this.renderBuildings, this)
或内联绑定
this.props.buildings.map(this.renderBuildings.bind(this))
小智 5
在做待办事项教程时,我在使用功能组件的 props 时也遇到了一些问题。当您使用功能组件而不是类组件时,如果您想使用 props,则必须从节点模块进行导入。将此行放在文件的顶部:
import props from 'prop-types';
Run Code Online (Sandbox Code Playgroud)
然后,当您想要在功能组件中使用 props 时,您首先需要将关键字作为该函数的参数传递。之后,您将可以像在类组件中一样使用它,但不使用关键字“this”:
function Todos(props) {
console.log(props.todos);
return (
<div className="Todos">
<h2>This is the Todos component</h2>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36129 次 |
最近记录: |