设置 React useReducer 的最佳方法 [英] Best way to setup a React useReducer
问题描述
我将这个 reducer.js 文件设置为使用 React 的 useReducer
I setup this reducer.js file to use React's useReducer
https://reactjs.org/docs/hooks-reference.html#usereducer
import {useReducer} from 'react';
const initialState = {
test: 0,
};
const reducer = (state, action) => {
switch (action.type) {
case 'reset':
return initialState;
case 'addTest':
return {test: state.test + 1};
case 'removeTest':
return {test: state.test - 1};
}
};
export const getReducer = () => {
return useReducer(reducer, initialState);
};
现在我可以在不同的渲染函数中通过 getReducer
获取状态和分派:
Now I can get state and dispatch via getReducer
in different rendering functions:
import React from 'react';
import ReactDOM from 'react-dom';
import {getReducer} from './reducer';
const Button = (props) => (
<button
type="button"
onClick={() => props.dispatch({type: props.type})}>
{props.children}
</button>
);
const App = () => {
const [state, dispatch] = getReducer();
return (
<React.Fragment>
{state.test}
<Button dispatch={dispatch} type="addTest">Add 1</Button>
<Button dispatch={dispatch} type="removeTest">Remove 1</Button>
<Button dispatch={dispatch} type="reset">Reset</Button>
</React.Fragment>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
传递dispatch
函数并让其他组件调用props.dispatch 确实感觉很奇怪.有没有更简洁的方法来设置?
It does feel weird passing the dispatch
function around and having other components call props.dispatch. Is there a cleaner way to set this up?
如果你想尝试不同的模式,我在这里设置了一个仓库:https://github.com/dancrew32/hooks
I setup a repo here if you want to try out different patterns: https://github.com/dancrew32/hooks
推荐答案
如何定义您的操作并将它们映射到您的减速器?
How about defining your actions and mapping them to your reducer?
const mapDispatch => dispatch => ({
reset: () => dispatch({ type: 'reset' }),
addTest: () => dispatch({ type: 'addTest' }),
removeTest: () => dispatch({ type: 'removeTest' })
})
const Button = (props) => (
<button
type="button"
onClick={props.onClick}>
{props.children}
</button>
);
const App = () => {
const [state, dispatch] = getReducer();
const actions = mapDispatch(dispatch)
return (
<React.Fragment>
{state.test}
<Button onClick={actions.addTest}>Add 1</Button>
<Button onClick={actions.removeTest}>Remove 1</Button>
<Button onClick={actions.reset}>Reset</Button>
</React.Fragment>
);
};
这里没有什么新鲜事;只是对 react-redux
如何做事的模仿.
Nothing new here; just a copycat of how react-redux
does things.
这篇关于设置 React useReducer 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!