这不是一个问题,而是一个问题。我只想将React用于我的全局状态管理,并通过useReducer和useContext传递待办事项,我想知道这是不是一种正确的方法。react编码器告诉我,这种方式会在组件不应该重新呈现时重新呈现组件,但我的元素检查只显示更改后的组件重新呈现。请指导我,我是否可以继续以这种方式开发,或者必须恢复到Mobx或redux或许多其他第三方状态管理器库。
发布于 2019-03-12 20:09:04
是的,多亏了新的钩子API,它变得比以往任何时候都更容易!对于非常简单的事情,例如,一个全局主题,你可以用React.createContext和useContext创建一个上下文。
要获得更健壮的解决方案,您实际上可以结合使用useContext和useReducer来实现Flux架构。这是我之前做的一个。
// AcmeContext.js
import React, { useReducer, createContext } from 'react'
const AcmeContext = createContext({})
const actions = {
DO_SOMETHING: 'doSomething'
}
const actionCreators = dispatch => ({
updateComment: comment => {
dispatch({
type: actions.DO_SOMETHING,
payload: comment
})
}
})
// first paramter is your state, second is the action
let reducer = (currentState, { type, payload }) => {
switch (type) {
case actions.DO_SOMETHING:
// important: return a NEW new object for this context, don't change the old currentState
return { ...currentState, hello: payload }
default:
return
}
}
// this component wraps any of the child components that you want to share state with
function AcmeProvider({ children, initialState }) {
const [state, dispatch] = useReducer(reducer, initialState)
const actions = actionCreators(dispatch)
return (
<AcmeContext.Provider value={{ state, actions }}>
{children}
</AcmeContext.Provider>
);
}
export { AcmeContext, AcmeProvider }然后,使用导出的提供程序包装要为其提供上下文的组件。
// App.jsx
import { AcmeProvider } from './AcmeContext'
import TestComponent from './TestComponent'
render((
<AcmeProvider initialState={{ hello: 'world' }}>
<TestComponent />
</AcmeProvider>
), document.querySelector('.app'))最后,您可以从子组件调用它。
// TestComponent.jsx
import { AcmeContext } from './AcmeContext'
export default () => {
const { state, actions } = useContext(AcmeContext)
return (
<div>
Hello {state.hello}!
<button onClick={() => actions.updateComment('me')}>Set response on onClick to 'me'</button>
</div>
)
}对于一个完整的Redux实现来说,这确实有几个缺点。你不会得到Redux开发工具,你也不会得到像redux-thunk这样的东西,这意味着你必须将该逻辑添加到组件中,并让组件更新上下文。
发布于 2019-03-12 19:30:31
是的,您完全可以使用默认的React API来对项目进行全面的状态管理。钩子的引入使其易于管理。useContext已经慢慢地成为我最喜欢的钩子,因为它消除了对消费者的需要,并使JSX看起来更好一点。
如果你担心重新渲染的次数太多,你仍然可以使用React工具箱中的所有技巧,比如React.memo。
https://stackoverflow.com/questions/55120324
复制相似问题