Redux源码中的编程技巧(一)之手动抛出异常帮助定位代码

Redux是一款优秀的状态管理库, 它的设计巧妙, 可扩展性强, API简单易懂. 或许会有很多人以为实现Redux的代码量会很多, 然而事实恰恰相反. Reudx的核心代码只包含了不到10个js文件, 其中还有3个文件是辅助函数. 在阅读Redux源码时, 本人发现其中有一些很有意思的编程技巧, 遂整理并发出来与大家分享.

src/utils.warning.js中, 有这样一段代码:

export default function warning(message) {
  /* eslint-disable no-console */
  if (typeof console !== 'undefined' && typeof console.error === 'function') {
    console.error(message)
  }
  /* eslint-enable no-console */
  try {
    // This error was thrown as a convenience so that if you enable
    // "break on all exceptions" in your console,
    // it would pause the execution at this line.
    throw new Error(message)
  } catch (e) {} // eslint-disable-line no-empty
}

其中的这段代码:

try {
  throw new Error(message)
} catch (e) {}

try 代码块中手动抛出一个异常, 并在捕获异常后不作任何处理. 如果源码中没有注释的话, 就会令人疑惑: 为什么要手动抛出一个异常呢? 而良心的注释告诉了读者, 这样处理时为了方便开发者定位出错的代码.

在使用Chrome的Debugger时, 开启 Pause on exceptions 选项, 并勾选其下方的 Pause On Caught Exceptions选项, 这样当代码中有任何异常(包括在 try 代码块中被捕获到的异常)抛出时, Debugger都会将代码暂停在抛出异常的那一行. 这样的话再结合查看调用栈, 就可以很快地定位到是哪里的代码出现了问题.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,让我来回答你的问题。 首先,需要在项目安装 redux 和 @reduxjs/toolkit: ``` npm install redux @reduxjs/toolkit ``` 接着,创建一个 reducer 文件(比如 counterSlice.js),定义一个初始状态和一个 reducer 函数: ``` import { createSlice } from '@reduxjs/toolkit' const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment: (state) => { state.value++ }, decrement: (state) => { state.value-- }, }, }) export const { increment, decrement } = counterSlice.actions export default counterSlice.reducer ``` 在 App.js 使用这个计数器: ``` import React from 'react' import { useSelector, useDispatch } from 'react-redux' import { increment, decrement } from './counterSlice' function App() { const count = useSelector((state) => state.counter.value) const dispatch = useDispatch() return ( <div> <h1>Counter: {count}</h1> <button onClick={() => dispatch(increment())}>+</button> <button onClick={() => dispatch(decrement())}>-</button> </div> ) } export default App ``` 最后,需要在应用程序的顶层使用 Redux 的 Provider 组件,以便将 store 注入到组件树: ``` import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { configureStore } from '@reduxjs/toolkit' import counterReducer from './counterSlice' import App from './App' const store = configureStore({ reducer: { counter: counterReducer, }, }) ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ) ``` 这样就完成了一个使用 Redux Toolkit 开发的计数器应用。希望我的回答对你有帮助

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值