这可能与我不了解JavaScript的工作原理(非常奇怪)有关,但是我真的不明白为什么会这样。我有这段React / React-select代码,几乎完全来自react-select自述文件:
class Status extends Component {
constructor(props) {
super(props)
this.state = {
selectedOption: null,
}
this.statusOptions = [];
}
handleChange = (selectedOption) => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
componentDidMount = () => {
console.log(this.statusOptions);
axios.get(host+'/StatusList')
.then((response) => {
for(var i = 0; i < response.data.status_list.length; i++) {
this.statusOptions.push({value: response.data.status_list[i][0], label: response.data.status_list[i][1]});
}
})
.catch((error) =>{
console.log(error)
})
.then(() =>{
});
}
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={this.statusOptions}
/>
);
}}
这不会填充我的react-select列表:但是,将列表/数组初始化移动到componentDidMount
可以使它起作用。为什么?
class Status extends Component {
constructor(props) {
super(props)
this.state = {
selectedOption: null,
}
}
handleChange = (selectedOption) => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
componentDidMount = () => {
this.statusOptions = [];
console.log(this.statusOptions);
axios.get(host+'/StatusList')
.then((response) => {
for(var i = 0; i < response.data.status_list.length; i++) {
this.statusOptions.push({value: response.data.status_list[i][0], label: response.data.status_list[i][1]});
}
})
.catch((error) =>{
console.log(error)
})
.then(() =>{
});
}
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={this.statusOptions}
/>
);
}}
答案 0 :(得分:1)
正确的方法是在React组件的状态下初始化statusOptions
属性,然后将其填充到Axios调用快乐路径中,以便setState
方法触发重新渲染填充选择组件。
class Status extends Component {
constructor(props) {
super(props)
this.state = {
selectedOption: null,
statusOptions: []
}
}
handleChange = (selectedOption) => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
componentDidMount = () => {
axios.get(host+'/StatusList')
.then((response) => {
const statusOptions = []
for(var i = 0; i < response.data.status_list.length; i++) {
statusOptions.push({value: response.data.status_list[i][0], label: response.data.status_list[i][1]});
}
this.setState({ statusOptions })
})
.catch((error) =>{
console.log(error)
})
}
render() {
const { selectedOption, statusOptions } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={statusOptions}
/>
);
}
}