我有一個父組件控制所有狀態和一個子組件,它返回一個下拉菜單並傳遞(應該傳遞,而不是)點擊一個選項的結果,直到父組件,並更新父母的狀態。反應下拉不設置狀態
家長:
// We're controlling all of our state here and using children
// components only to return lists and handle AJAX calls.
import React, { Component } from 'react';
import SubList from './SubList';
import StopList from './StopList';
class SubCheck extends Component {
constructor (props) {
super(props);
this.state = {
selectedSub: null,
selectedStop: null,
stops: [],
};
this.handleSubSelect.bind(this);
this.handleStopSelect.bind(this);
}
// We want the user to be able to select their specific subway
// stop, so obviously a different array of stops needs to be
// loaded for each subway. We're getting those from utils/stops.json.
handleSubSelect(event) {
var stopData = require('../utils/stops');
var stopsArray = [];
for (var i = 0; i < stopData.length; i++) {
var stop = stopData[i];
if (stop.stop_id.charAt(0) == event.target.onSubSelect) {
stopsArray.push(stop.stop_name);
}
}
this.setState(() => {
console.log('setting state');
return {
selectedSub: event.target.onSubSelect,
stops: stopsArray
}
});
}
handleStopSelect(event) {
this.setState({selectedStop: event.target.onStopSelect});
}
render() {
return (
<div>
<SubList onSubSelect={this.handleSubSelect.bind(this)}/>
<StopList stops={this.state.stops} onStopSelect={this.handleStopSelect.bind(this)}/>
</div>
);
}
}
export default SubCheck;
兒童:
import React from 'react';
import PropTypes from 'prop-types';
function SubList (props) {
const subways = ['', '1', '2', '3', '4', '5', '6',
'S', 'C', 'B', 'D', 'N', 'Q', 'R', 'L']
return (
<select>
{
subways.map(subway =>
<option key={subway} onClick={() => props.onSubSelect(subway)}>
{subway}
</option>
)
}
</select>
)
}
SubList.PropTypes = {
onSubSelect: React.PropTypes.func.isRequired
};
export default SubList;
當我打開應用程序的是,選擇從下拉菜單中的選項,兩件事情不會發生,我會希望發生。一個是第二個菜單(由StopList返回的,其代碼未包含在此)沒有填充任何數據。第二件事是'設置狀態'沒有記錄到控制檯。第二件事是讓我相信在我的代碼的某個地方,我沒有正確地將下拉選項中的選項傳遞給我的handleSubSelect方法,因此沒有正確設置任何新的狀態。
哪裏是'StopList'的代碼?它究竟做了什麼? – Dekel