【发布时间】:2020-09-02 14:20:13
【问题描述】:
当屏幕首次加载时,我从服务器获取一些信息并设置状态。如果用户使用选择菜单并选择了其他东西,它会改变状态。
所以,我基本上想说的是,如果状态值来自服务器,则显示该状态值,或者如果状态值来自用户选择,请使用它。我也在尝试使用 && 来确保首先有一个可用的值。
const [country, setCountry] = useState();
useEffect(() => {
// get location via public IP lookup and set state of country c
//calling code based on IP eg: +44
setCountry(countryInfo.data);
}, []);
<Input
name="countryCode"
placeholder={
country && country.location.calling_code ? country.location.calling_code : country.callingCode }
width="20%"
editable={false}
/>
<CountryPicker
name="country"
theme={{ fontSize: 14, padding: 30 }}
countryCode={
country && country.country_code
? country.country_code
: country && country.cca2
}
withCallingCode
withFilter
withCountryNameButton={true}
withFlagButton={false}
withFlag={false}
withEmoji={false}
onSelect={(country) => setCountry(country)}
/>
country.location.calling_code 在初始加载时来自服务器,country.callingCode 是如果用户决定通过下拉列表更改它。
我得到的错误是:
undefined 不是对象(评估 country.location.calling_code)
【问题讨论】:
-
看看这个组件的其余相关代码会很有帮助。
-
最后有一个重复的
: country.callingCode,这是错字吗? -
对不起,是的。我现在删除了一个副本
-
在访问
calling_code之前,您正在检查country但不是country.location。真的有location属性吗? -
另外,您应该包含minimal reproducible example,如果我们无法重现我们这边的问题,我们将无法真正帮助您。你是如何设置状态的?它是如何传递给这个组件的?等等
标签: javascript reactjs