返回

在Taro中使用MobX轻松构建天气微信小程序

前端

技术栈选用 Taro + mobx + TypeScript,接口来自 Yahoo Weather API,设计上参考了 Yahoo Weather。

Taro + MobX开发优势

Taro 是一个开放式跨端框架,能够构建微信小程序、H5、ReactNative 等多种平台的应用。MobX 是一个状态管理库,它可以帮助你轻松管理应用程序的状态。TypeScript 是一种类型化的编程语言,它可以帮助你编写更健壮的代码。

实现步骤

  1. 创建 Taro 项目
taro init my-app
  1. 安装必要的依赖项
npm install taro-mobx mobx @types/mobx
  1. 创建一个新的 MobX 存储
// store.js
import { observable, action } from "mobx";

class Store {
  @observable weather = {
    temperature: 0,
    city: "",
    condition: "",
  };

  @action
  setWeather(weather) {
    this.weather = weather;
  }
}

export default new Store();
  1. 在 Taro 组件中使用 MobX 存储
// app.js
import Taro, { Component } from "@tarojs/taro";
import { Provider } from "mobx-react";
import store from "./store";

class App extends Component {
  render() {
    return (
      <Provider store={store}>
        {this.props.children}
      </Provider>
    );
  }
}

export default App;
// weather.js
import Taro, { Component } from "@tarojs/taro";
import { observer } from "mobx-react";
import store from "./store";

@observer
class Weather extends Component {
  render() {
    const { weather } = store;
    return (
      <div>
        <h1>{weather.city}</h1>
        <p>{weather.temperature}°C</p>
        <p>{weather.condition}</p>
      </div>
    );
  }
}

export default Weather;
  1. 使用 Yahoo Weather API 获取天气数据
// api.js
import axios from "axios";

const API_KEY = "你的 API key";

export const getWeather = (city) => {
  return axios.get(
    `https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="${city}")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys`
  );
};
  1. 在 Taro 组件中使用 API 获取天气数据
// weather.js
import Taro, { Component } from "@tarojs/taro";
import { observer } from "mobx-react";
import store from "./store";
import { getWeather } from "./api";

@observer
class Weather extends Component {
  componentDidMount() {
    getWeather("上海").then((res) => {
      store.setWeather(res.data.query.results.channel.item.condition);
    });
  }

  render() {
    const { weather } = store;
    return (
      <div>
        <h1>{weather.city}</h1>
        <p>{weather.temperature}°C</p>
        <p>{weather.condition}</p>
      </div>
    );
  }
}

export default Weather;

结语

以上就是使用Taro+MobX+TypeScript+Yahoo Weather API构建天气微信小程序的详细步骤。