现在,最愚蠢的事情发生在我的代码上。我有一个项目列表呈现在DOM中,我需要把一个按钮,以调用另一个函数,如果我把按钮这样<button></button>一切正常,但如果我分配一个功能到该按钮,然后一切都下来<button onClick={function}></button>我会告诉你我的代码,看
<button></button>
<button onClick={function}></button>
@connectToStores export default class Dealers extends Component { static contextTypes = { router : React.PropTypes.func, } static propTypes = { title : React.PropTypes.func, } constructor (props) { super(props); this.state = { modal : false, } } static getStores () { return [ GetDealersStore ]; } static getPropsFromStores () { return GetDealersStore.getState(); } render () { let dealersInfo; if (this.props.dealerData !== null) { dealersInfo = this.props.dealerData.dealersData.map(function(dealer) { return (<div key={dealer.DealerId} style={Styles.dealerCard}> <Card> <CardHeader title={dealer.NickName} subtitle={dealer.DealerId} avatar={dealer.Picture}/> <CardText> <FloatingActionButton> //////////////////////// <IconAdd /> //////THIS IS THE BUTTON///// </FloatingActionButton>////////////////////// </CardText> </Card> </div> ); }); } else { dealersInfo = <p>Loading . . .</p>; } return ( <Grid> <Row> <Column><h4>Dealers</h4></Column> </Row> <div style={Styles.mainCont}> {dealersInfo} </div> </Grid> ); } componentWillMount () { GetDealersActions.getDealers(); } _openUpdateDealer = () => { console.log(123); } }
如您所见,有一条声明
if (this.props.dealerData !== null) { ... }else { dealersInfo = <p>Loading . . .</p>; }
正如我上面粘贴的一切代码工作真棒,但如果添加了<FloatingActionButton onClick={this._openUpdateDealer.bind(this)}><IconAdd /></FloatingActionButton>那么一切都发生故障,所有我在屏幕上看到的是Loading . . .这是else在上面的语句。
<FloatingActionButton onClick={this._openUpdateDealer.bind(this)}><IconAdd /></FloatingActionButton>
Loading . . .
else
所以,我想知道,这里发生了什么反应?
您正在.map操作中间渲染按钮:
.map
this.props.dealerData.dealersData.map(function(dealer) {
它使用不同的值this; 因此,this.props在函数内部不存在。我希望能cannot read property dealerData of undefined在浏览器控制台中看到。
this
this.props
cannot read property dealerData of undefined
您需要使用可选thisArg参数:
thisArg
this.props.dealerData.dealersData.map(function(dealer) { // ... }, this);
将映射功能this手动绑定:
this.props.dealerData.dealersData.map(function(dealer) { // ... }.bind(this));
或使用箭头功能(因为您正在使用ES6功能):
this.props.dealerData.dealersData.map((dealer) => { // ... });