【发布时间】:2021-11-03 22:54:08
【问题描述】:
我有一个来自 reactstrap 的 CustomInput,单击时未显示正确的 state.name。我将 stringifiedJSON 对象作为选项的值传递,然后句柄更改将字符串解析回对象。我可以 console.log(state) 并很好地查看对象。
如果我将 onChange 设置为 onChange={({target}) => setCountry(target.value)} 这将正确呈现所选选项,如果我选择美国,它会显示美国,如果我选择墨西哥,它会显示墨西哥,依此类推。
但是,当我将我的 onChange 设置为 onChange={handleChange} 并且 handleChange 在下面时,它只会显示数组中的第一项,在我的情况下是美国。我可以选择墨西哥,console.log 会显示更新的状态,但是选择选项看起来仍然选择美国。
const handleChange = async(event) => {
setCountry(event.target.value)
const obj = JSON.parse(event.target.value)
setCountry(obj)
}
<Input
type="select"
id="country"
name="country"
className="mb-3"
value={country}
onChange={({target}) => setCountry(target.value)} <--- this renders correctly
>
{numberCountries.map((country, index) => (
<Fragment>
<option key={index} value={JSON.stringify(country)}>{country?.name}</option>
</Fragment>
))}
<Input
type="select"
id="country"
name="country"
className="mb-3"
value={country}
onChange={handleChange} <--- this calls update state and updates correctly but the select option wont render the correct country.name.
>
{numberCountries.map((country, index) => (
<Fragment>
<option key={index} value={JSON.stringify(country)}>{country?.name}</option>
</Fragment>
))}
</Input>
这是为选项映射的 numberCountries
[
{
name: 'United States',
countryCode: 'US',
areaCodes: AreaCodes,
type: {
local: {
amount: '400'
},
toll_free: {
amount: '400'
},
}
},
{
name: 'Australia',
countryCode: 'AU',
type: {
local: {
amount: '1500'
},
}
},
{
name: 'Belgium',
countryCode: 'BE',
type: {
local: {
price: '410'
},
}
}
]
【问题讨论】:
-
你作为
value属性传递给Input组件的typeof country是什么? -
我刚刚加了
标签: javascript reactjs