gpt4 book ai didi

javascript - state.map(state, i) 给出未定义

转载 作者:行者123 更新时间:2023-12-03 01:47:55 29 4
gpt4 key购买 nike

您好,我正在尝试使用 map 根据我所在状态的数组渲染选项,但在返回中使用它时我得到未定义

这是数组

this.state = {   countries: ["Australia","Brazil","China","Sweden"]}

我尝试这样使用它

this.state.countries.map((country, i) =>
<option value={this.state.countries[i]}>{this.state.countries[i]}</option>)

但我得到i is undefined。我也尝试仅使用国家/地区,但总是未定义。但如果我在我的渲染中这样做

this.state.countries.map((country, i) => console.log(country + " " + i));

我的国家/地区和 i 都是正确的。为什么我不能使用返回值?

这是整个组件

    class BoxForm extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
weight: "",
color: "",
country: "",
countries: ["Australia","Brazil","China","Sweden"]
}
this.handleNameChange = this.handleNameChange.bind(this);
this.handleWeightChange = this.handleWeightChange.bind(this);

}
handleNameChange(e) {
this.setState({ name: e.target.value });
}
handleWeightChange(e) {
this.setState({ weight: e.target.value });
}

render() {
this.state.countries.map((country, i) => console.log(country + " " + i));
return (
<div className="formGroup">
<form>
<FormGroup>
<h4 className="nameHeader">Name</h4>
<FormControl
className="textfield"
type="text"
value={this.state.name}
placeholder="Enter text"
onChange={this.handleNameChange}
/>
<h4 className="weightHeader">Weight</h4>
<FormControl
className="textfield"
type="number"
value={this.state.weight}
placeholder="Enter text"
onChange={this.handleWeightChange}
/>
<h4 className="colorHeader">Box Color</h4>
<FormControl
className="textfield"
type="text"
value={this.state.color}
placeholder="Enter text"
/>
<h4 className="destinationHeader">Destination Country</h4>
<FormControl
componentClass="select"
className="textfield"
type="dropdown"
value={this.state.country}
placeholder="Enter text"
>
this.state.countries.map((country, i) =>
<option value={this.state.countries[i]}>{this.state.countries[i]}</option>)
</FormControl>
</FormGroup>
</form>
</div>
);
}
}

export default BoxForm;

最佳答案

您需要用 {} 包装从 map 返回的数组

<FormControl
componentClass="select"
className="textfield"
type="dropdown"
value={this.state.country}
placeholder="Enter text"
>
{this.state.countries.map((country, i) => (
<option value={country}>{country}</option>
))}
</FormControl>;

关于javascript - state.map(state, i) 给出未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50550956/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com