2020-03-19
问题
使用 Taro + Mobx,对数组进行增删改后,在数组中使用子组件,界面没有按照数组结果进行渲染。
问题代码
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>