【发布时间】:2019-06-27 16:31:08
【问题描述】:
无法合并...状态和函数返回的结果。
我正在尝试将类组件更改为功能组件。
所以我更新了 react 并使用了钩子。
首先我想改变类的状态,setState 来挂钩那些。
但是钩子的 setState 替换 oject 不像类的 setState 那样合并。
下面是原代码
import React from 'react'
import produce from 'immer'
import {
getUserFromCookie,
login,
logout,
profile,
updateProfile
} from '../api'
const userInfo = getUserFromCookie()
const UserContext = React.createContext({
...userInfo
})
export const withUserContext = WrappedComponent => {
return class ProviderComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
...userInfo,
consentNeeded: false,
updateConsent: async ({ pi, news, seen }) => {
await updateProfile({ pi, news, seen })
this.setState({
consentNeeded: false
})
},
profile: async () => {
const userProfile = await profile()
if (userProfile.seen_consent_modal === false) {
this.setState({
consentNeeded: true
})
}
},
login: async ({ userId, password }) => {
const user = await login({ userId, password })
this.setState(
produce(draft => {
return user
})
)
},
logout: async () => {
await logout()
}
}
}
render() {
return (
<UserContext.Provider value={this.state}>
<WrappedComponent {...this.props} />
</UserContext.Provider>
)
}
}
}
export default UserContext
这是我工作的功能组件。
import React, { useState } from 'react'
import produce from 'immer'
import {
getUserFromCookie,
login,
logout,
profile,
updateProfile
} from '../api'
const userInfo = getUserFromCookie()
const UserContext = React.createContext({
...userInfo
})
export const withUserContext = WrappedComponent => {
return function provideComponent() {
const [state, setState] = useState({
...userInfo,
consentNeeded: false,
updateConsent: async ({ pi, news, seen }) => {
console.error('updateConsent!!')
await updateProfile({ pi, news, seen })
setState({
consentNeeded: false
})
},
profile: async () => {
console.error('profile!!')
const userProfile = await profile()
if (userProfile.seen_consent_modal === false) {
setState({
consentNeeded: true
})
}
},
login: async ({ userId, password }) => {
const user = await login({ userId, password })
setState(
produce(() => user)
)
},
logout: async () => {
await logout()
}
})
return (
<UserContext.Provider value={state}>
<WrappedComponent {...props} />
</UserContext.Provider>
)
}
}
export default UserContext
下划线警告..我认为它的语法不正确
【问题讨论】:
-
你为什么把
async函数放在初始state的值里面?你希望他们怎么称呼?什么时候?更好地附加基于源类的组件(但不是所有内容 - 只需单个state的键和加载就足够的函数) -
现在我可以说看起来像滥用
useState- 它的参数是一些状态数据的初始值,就像你可以在构造函数中为基于类的组件初始化它一样:this.state = { .... };基于道具。这里也是一样。所以通常你不想在那里有函数。 -
我建议你,对于复杂的组件使用类组件!功能组件有不同的用例......在这里你应该写 {...state, *****} 而不是 {...userInfo, *****}
标签: reactjs react-hooks