0
我有一個組件,其中我試圖用我的道具中的一些選項填充<Select />
組件。當組件掛載時,我將jobNumbers
的狀態設置爲空數組。React - Redux窗體 - 狀態得到設置,但幾乎立即重置
我有兩個下拉列表,其值取決於另一個選定的值。當選擇該值時,我運行一個onChange
函數來填充第二個下拉列表。唯一的問題是當我做this.setState({jobNumbers: [...array elements...]})
時,狀態仍然顯示jobNumbers
數組爲空。實際進行狀態設置的功能是getCustomerOptions()
。
這裏是我的組件在它的全部內容(這不是太可怕長)
import React from 'react';
import SelectInput from '../../components/SelectInput';
import LocationSelector from '../../components/LocationSelector';
import { Field } from 'redux-form/immutable';
import Select from 'react-select';
import 'react-select/dist/react-select.css';
class InputCurrentCustomerLocation extends React.Component {
constructor(props) {
super(props);
this.state = {
jobNumbers: [],
};
this.getCustomerOptions = this.getCustomerOptions.bind(this);
this.onChange = this.onChange.bind(this);
}
componentWillMount() {
if (this.props.active) {
this.props.input.onChange(this.props.active);
}
}
onChange(event) {
if (this.props.input.onChange) {
this.props.input.onChange(event.value); // <-- To be aligned with how redux-form publishes its CHANGE action payload. The event received is an object with 2 keys: "value" and "label"
// Fetch our Locations for this customer
this.props.handleCustomerLocationFetch(event.value);
this.getCustomerOptions(event);
}
}
getCustomerOptions(event) {
let options = [];
if(event) {
this.props.options.forEach((option, index) => {
if(option.value === event.value) {
console.log('props options', this.state);
this.setState({ jobNumbers: this.props.options[index] });
console.log('state options', this.state);
}
})
}
}
render() {
const { meta } = this.props;
return (
<div>
<Select
options={this.props.options} // <-- Receive options from the form
{...this.props}
value={this.props.input.value || ''}
// onBlur={() => this.props.input.onBlur(this.props.input.value)}
onChange={this.onChange.bind(this)}
clearable={false}
/>
{meta.error && <div className="form-error">{meta.error}</div>}
{this.props.activeLocations ? false : (
<div>
<div>
<p> Select a location </p>
<Field
name="locations"
component={props =>
<LocationSelector
{...props}
// active={this.props.activeLocations}
locations={this.props.locations}
/>
}
/>
</div>
<div>
<p> Select a job number</p>
<Field
name="jobNumber"
component={props =>
<Select
options={this.state.jobNumbers}
value={this.props.input.value || ''}
onChange={this.onChange.bind(this)}
clearable={false}
/>
}
/>
</div>
</div>
)}
</div>
);
}
}
export default InputCurrentCustomerLocation;
我是比較新的反應,終極版,我不完全知道爲什麼發生這種情況。國家不應該填充?
你爲什麼要在forEach中調用setState? –
截至目前,這是如何檢查一場比賽是如何發生的,只有在比賽中應該設置狀態。我最終要做的就是訪問'this.props.options'中的特定索引。這是否需要國家的東西? –