请参阅下面的片段。
通过做这个:
React.useState(()=>getInitialState2());
您避免在每次渲染时运行getInitialState2()
used 。useState
但这似乎不起作用useReducer
。
问题
有没有办法避免在每次渲染的钩子上运行initialState
参数中使用的函数?useReducer
function App() {
const [state,dispatch] = React.useReducer(reducer,getInitialState());
const [state2,setState2] = React.useState(()=>getInitialState2());
return(
<React.Fragment>
<div>
State: {state}
</div>
<div>
State2: {state2}
</div>
<div>
<button onClick={() => dispatch({type: "INCREMENT"})}>+</button>
<button onClick={() => dispatch({type: "DECREMENT"})}>-</button>
</div>
</React.Fragment>
);
}
function getInitialState() {
console.log("From getInitialState...");
return 0;
}
function getInitialState2() {
console.log("From getInitialState2...");
return 0;
}
function reducer(state,action) {
switch(action.type) {
case "INCREMENT": {
return state + 1;
}
case "DECREMENT": {
return state - 1;
}
default: {
return state;
}
}
}
ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>