[英]How can I initialize Redux state for React component on its creation?
[英]How can I initialize state inside a React Component for an integer data type?
我正在尝试在我的一个 React 组件中为 integer 数据类型初始化 state 。 现在我的 state 看起来像这样:
state = {
username: '',
email: '',
password: '',
user_id: null,
id: null,
toy_id: null,
loading: false,
}
因为它们不是字符串,所以我一直将null
用于user_id
、 id
和toy_id
,但是后来当我传递属性时:
const { email, password, user_id, id, toy_id } = this.state
// ...
await this.props.loginUserToy(email, password, id, toy_id)
console.log('LOGIN loginUserToy email', email)
console.log('LOGIN loginUserToy password', password)
console.log('LOGIN loginUserToy id', id)
console.log('LOGIN loginUserToy toy_id', toy_id)
这是我的动作创建者页面中的loginUserToy
:
export const loginUserToy = async (email, password, id, toy_id) => {
try {
const response = await axios({
method: 'POST',
url: `${API_URL}/api/get_token`,
data: {
email,
password
}
})
const { token } = response.data
const userResponse = await axios({
method: 'POST',
url: `${API_URL}/api/login`,
headers: {
Authorization: `${token}`
},
data: {
email,
password
}
})
const getProfileResponse = await axios({
method: 'POST',
//url: `${API_URL}/api/user_profile`,
url: `${API_URL}/api/toy`,
headers: {
Authorization: `${token}`
},
data: {
id,
toy_id
}
})
const { Name, Description, Where, When, Picture } = getProfileResponse.data
return {
type: FETCH_TOY,
payload: {
token,
email,
password,
id,
toy_id,
name: Name,
description: Description,
location: Where,
date: When,
image: Picture
}
}
}
catch (err) {
console.log('Exception in actions/user/loginUser err', err)
}
}
我为前两个日志返回“t”和“t”(这是正确的),但我继续为后两个日志返回null
。 我了解空字符串与null
不同,这意味着不存在的值。
但是,我还能在这里做些什么吗?
尝试简单地将它们初始化为0
而不是null
。
state = {
username: '',
email: '',
password: '',
user_id: 0
id: 0,
toy_id: 0,
loading: false,
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.