background

Recently, I have been using Taro to make a small program for wechat, which inevitably requires rich text, and the rich text basically uses wxParse. And I had a problem with the combination of the two.

The problem

Specific see github.com/NervJS/taro… In general, after wxParse parses rich text, under certain circumstances (under what circumstances?) , the node content will be lost.

// wxparse. TSX, props:{content: string} export default class ParseComponent extends Component<IProps> { componentDidMount() { const { content } = this.props; WxParse.wxParse('content', 'html', content, this.$scope, 5); } render() { return ( <View> <import src='.. /.. /components/wxParse/wxParse.wxml' /> <template is='wxParse' data='{{wxParseData:content.nodes}}' /> </View> ); }}Copy the code

Then the big guy came up with the solution, parsed it again at componentDidUpdate, and asked me to see the implementation of wxParse.

// wxParse.tsx export default class ParseComponent extends Component<IProps> { ... componentDidUpdate() { const { content } = this.props; WxParse.wxParse('content', 'html', content, this.$scope, 5); }... }Copy the code

Understand the implementation of wxParse

In the wxParse template, find the key implementation, wxparse.wxml, in line 41

<! -- Entry template -->
<template name="wxParse">
  <block wx:for="{{wxParseData}}" wx:key="">
    <template is="wxParse0" data="{{item}}" />
  </block>
</template>
Copy the code

You can see that parsing starts with traversing wxParseData, where does this wxParseData come from? Wxparse.wxparse (…) wxparse.tsx Internally, this method uses setData to write parsed data to the component. The key codes are as follows:

/ / wxParse. Js 31 rows
var transData = {};// Store converted data
var bindData = {};
bindData[bindName] = transData; // bindName is the key value, which corresponds to 'content' according to what I wrote
that.setData(bindData) // That is component object
Copy the code

The specific reason

When the wxparse. TSX component is hanging, print the parse content and you can see that the parse content exists.

When our parent component updated, it caused the child component wxparse. TSX to update, and we didn’t do anything special (reparsing the props pass), so the data looked like this

The answer is clear: Nodes in wxParseData is empty, and the template traversal is empty.

The last

Or thank you for taking the time to answer the question, but also their own art is not fine performance, still need a lot of efforts ~