我正在编写一个react应用程序redux,避免使用react-redux,如果我们手动处理所有调度的事件,这在技术上是可行的。这是示例代码。
这index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.6.0/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"></script>
</head>
<body>
<div id="app"></div>
<script>
const appState= {
count: 0,
}
const reducer = (state, action) => {
if (typeof state === 'undefined') state = appState;
switch (action.type) {
case 'INCREMENT':
return {count: state.count+1}
case 'DECREMENT':
return {count: state.count-1}
default:
return state
}
}
var store = Redux.createStore(reducer);
const App = () => {
const [val, setVal] = React.useState(0);
handleClick = () => {
store.dispatch({type: 'INCREMENT'})
}
const unsubscribe = store.subscribe(() => {
const state = store.getState();
console.log("Listener is called")
setVal(state.count);
});
/* unsubscribe() */;
return (
<div>
<span>{val}</span>
<button onClick={handleClick}>Click</button>
</div>
);
}
ReactDOM.render(<App />, document.querySelector("#app"))
</script>
</body>
</html>
在这里,如果我第一次单击按钮,它会将日志打印到控制台一次,但是当我第二次单击按钮时,它会在日志上打印两次语句,这表明来自订阅的回调被调用了两次,为什么会这样我该如何防止呢?
守着星空守着你
相关分类