Mobx 环境搭建=>入门详解=>项目中应用(react中使用mobx)

本文详细介绍了如何搭建Mobx环境,包括Webpack配置和HTML设置。接着,深入讲解了Mobx的核心概念,如observable、observable装饰器、响应式计算和状态改变。在React中使用Mobx,通过mobx-react库,展示了如何在组件中应用Mobx。最后,文章提到了在项目中的实际应用,包括入口文件和组件的编写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mobx

Mobx是一个功能强大,上手非常容易的状态管理工具。redux的作者也曾经向大家推荐过它,在不少情况下可以使用Mobx来替代掉redux。
在这里插入图片描述

这张图来自于官网,把这张图理解清楚了。基本上对于mobx的理解就算入门了。

官网有明确的核心概念使用方法,并配有egghead的视频教程。这里就不一一赘述了。

要特别注意当使用 mobx-react 时可以定义一个新的生命周期钩子函数 componentWillReact。当组件因为它观察的数据发生了改变,它会安排重新渲染,这个时候 componentWillReact 会被触发。这使得它很容易追溯渲染并找到导致渲染的操作(action)。

  • componentWillReact 不接收参数

  • componentWillReact 初始化渲染前不会触发 (使用 componentWillMount 替代)

  • componentWillReact 对于 mobx-react@4+, 当接收新的 props 时并在 setState 调用后会触发此钩子

  • 要触发componentWillReact必须在render里面用到被观察的变量

  • 使用Mobx之后不会触发componentWillReceiveProps

1、搭建环境

mkdir my-app
cd my-app
npm init -y
npm i webpack webpack-cli webpack-dev-server -D
npm i html-webpack-plugin -D
npm i babel-loader @babel/core @babel/preset-env -D
npm i @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties -D
npm i @babel/plugin-transform-runtime -D
npm i @babel/runtime -S
npm i mobx -S
mkdir src
mkdir dist
touch index.html
touch src/index.js
touch webpack.config.js

编写webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
   
  mode: 'development',
  entry: path.resolve(__dirname, 'src/index.js'),
  output: {
   
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js'
  },
  module: {
   
    rules: [
      {
   
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
   
          loader: 'babel-loader',
          options: {
   
            presets: ['@babel/preset-env'],
            plugins: [
              //支持装饰器
              ["@babel/plugin-proposal-decorators", {
    "legacy": true }],
              ["@babel/plugin-proposal-class-properties", {
    "loose" : true }],
              ['@babel/plugin-transform-runtime']
            ]
          }
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin()],
  devtool: 'inline-source-map'
}

编写index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值