🎶 Sym - 一款用 Java 实现的现代化社区(论坛/BBS/社交网络/博客)平台

📕 思源笔记 - 一款桌面端笔记应用,支持 Windows、Mac 和 Linux

🎸 Solo - B3log 分布式社区的博客端节点,欢迎加入下一代社区网络

♏ Vditor - 一款浏览器端的 Markdown 编辑器

Taro + Mobx 支付宝小程序数组中自定义组件渲染异常

2020-03-19

问题

使用 Taro + Mobx,对数组进行增删改后,在数组中使用子组件,界面没有按照数组结果进行渲染。

imageyaj6OWF.png

问题代码

src/app.tsx

import Taro, { Component, Config } from '@tarojs/taro';
import {listStore} from "./store/list";
import {Provider} from "@tarojs/mobx";
import Index from './pages/list';

export const store = {
  list: listStore,
};

class App extends Component {
  config: Config = {
    pages: [
      'pages/list',
    ],
  };

  componentDidMount() {}

  componentDidCatchError() {}
  render() {
    return (
      <Provider store={store}>
        <Index />
      </Provider>
    );
  }
}

Taro.render(<App />, document.getElementById('app'));

src/store/list.ts

import {action, observable} from "mobx";
import { toJS } from 'mobx';

let count = 0;
export class ListStore {
  @observable list: string[] = [];

  @action.bound
  addTestItem() {
    const newList = toJS(this.list).slice(0);
    newList.unshift(String(count));
    count++;
    this.list = newList;
  }

  @action.bound
  deleteItem() {
    const newList = toJS(this.list).slice(0);
    newList.shift();
    this.list = newList;
  }
}

export const listStore = new ListStore();

src/pages/list.tsx

import {Button, View} from "@tarojs/components";
import {toJS} from "mobx";
import {ListStore} from "../store/list";
import {inject, observer} from "@tarojs/mobx";
import Component = Taro.Component;
import Item from "../components/Item"
import {ComponentType} from "react";

interface IProps {
  list: ListStore;
}

@inject('list')
@observer
class List extends Component<IProps> {
  add = async () => {
    const {list} = this.props;
    list.addTestItem();
  };

  delete = async () => {
    const {list} = this.props;

    list.deleteItem();
  };

  render() {
    const list = toJS(this.props.list.list) || [];
    return (
      <View>
        <Button onClick={this.add}>add</Button>
        <Button onClick={this.delete}>delete</Button>
        {list.map(count => (
          <Item key={count} number={count}/>
        ))}
      </View>
    );
  }
}

export default List as ComponentType;

src/components/Item.tsx

import Taro, { Component} from '@tarojs/taro';
import {observer} from "@tarojs/mobx";
import {View} from "@tarojs/components";

interface IProps {
  number: string;
}

@observer
class Item extends Component<IProps> {
  render() {
    const { number } = this.props;
    return <View>{`number: ${number}`}</View>;
  }
}

export default Item;

解决

src/pages/list.tsx 子组件外添加标签 <View> 后可正常渲染

<View>
  <Item key={count} number={count}/>
</View>

imagejRiEZ3T.png

返回总目录

每天 30 秒系列之小八哥


欢迎注册黑客派社区,开启你的博客之旅。让学习和分享成为一种习惯!

留下你的脚步