问题
I'm trying to figure out the best way to use redux with react hooks. I saw the following
How to use React hooks + Redux
However I'm not convinced this is the best way to go. Does anyone have any alternative ideas?
I also saw the following and seems quite good. https://www.npmjs.com/package/redux-react-hook
Thanks
回答1:
The official react-redux package provide hooks since v7.1. Redux hooks can be used instead of the connect(mapStateToProps, mapDispatchToProps) function.
useSelector()
Extract data from the Redux store state using a selector function.
useDispatch()
Return a reference to dispatch that can be used to dispatch actions.
This is an example implementing a counter where the counter value is managed by Redux.
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
export const CounterComponent = () => {
const dispatch = useDispatch();
const counter = useSelector(state => state.counter);
return (
<div>
<span>{counter}</span>
<button onClick={() => dispatch({ type: 'INCREMENT_COUNTER' })}>
Increment counter
</button>
</div>
);
}
Source: https://react-redux.js.org/api/hooks
回答2:
you dont need to use redux with hooks to manage the state,you can create the similar using the combination of context api and custom hooks
const initialState = {
stateSet: false,
plan: {
}
}
const AppReducer = (state = initialState, action) => {
return {
plan: planReducer(state.plan, action)
}
}
const AppProvider = (props) => {
const [state, dispatch] = useReducer(AppReducer, initialState);
return (
<AppStateContext.Provider value={state}>
<AppDispatchContext.Provider value={dispatch}>
{props.children}
</AppDispatchContext.Provider>
</AppStateContext.Provider>
)
}
const useAppState = () => {
const context = React.useContext(AppStateContext);
return context;
}
const useAppDispatch = () => {
const context = React.useContext(AppDispatchContext);
return context;
}
then inside your component, you can any component
const { plan } = useAppState();
dispatch({ type: 'updateBusinessInfo', payload: { businessInfo: businessInfo, addOnsInfo: addOnsInfo } });
refer https://kentcdodds.com/blog/how-to-use-react-context-effectively fantastic post by kencdoods for details
回答3:
At the time of writing this is still in alpha stage, if you want to try it update your react-redux to v7.1.0-alpha.4.
https://react-redux.js.org/next/api/hooks#hooks
回答4:
After doing this recently myself I posted this
How to connect redux store using useSelector() when input fields already mapped using useState()
Make sure you npm I react-redux@next
Cheers
来源:https://stackoverflow.com/questions/55387568/using-redux-with-react-hooks