Skip to main content

Lifecycle

Mini program supports development using React, but it is slightly different from using React in the browser.

The entry component#

Every mini program application requires an entry component to register the application, and the default entry file is app.js in the src directory.

The entry component must export a React component. In the entry component we can set the global state or access the lifecycle of the entry instance: the

file: app.js

import React, { Component } from 'react'
// Suppose we want to use Reduximport { Provider } from 'react-redux'import configStore from '. /store'
// Global stylesimport '. /app.css'
const store = configStore()
class App extends Component {  // All React component methods can be used  componentDidMount() {}
  // Triggered when the app is launched  onLaunch() {}
  // Trigger when the app did show  componentDidShow() {}
  // Trigger when the app did hide  componentDidHide() {}
  render() {    // Nothing will be rendered in the entry component, but we can do something like state management here    return (      <Provider store={store}>        /* this.props.children is the page that will be rendered */        {this.props.children}      </Provider>    )  }}
export default App

Entry configuration#

We can add a new app.config.js file for global configuration, and the default export of app.config.js is the global configuration.

The configuration specification is based on the global configuration of the mini program.

file: app.config.js

export default {  pages: ['pages/index/index'],  window: {    backgroundTextStyle: 'light',    navigationBarBackgroundColor: '#fff',    navigationBarTitleText: 'Title',    navigationBarTextStyle: 'black',  },}

onLaunch ()#

Trigger when the app is launched.

componentDidShow ()#

Triggered when the program is launched, or when the foreground is cut.

componentDidHide ()#

Triggered when the application cuts the background.

onPageNotFound (Object)#

Triggered when the page to be opened by the application does not exist.

Parameters#

Object#
PropertyTypeDescription
pathstringPath to the page that does not exist
queryObjectThe query parameter to open a non-existent page
isEntryPagebooleanWhether it is the first page launched this time

Page components#

Every mini program includes at least one page component that can jump through the route and access the lifecycle of the mini program's page.

Class Component

import React, { Component } from 'react'import { View } from '@binance/mp-components'
class Index extends Component {  // All React component methods can be used  componentDidMount() {}
  // onLoad  onLoad() {}
  onTabItemTap() {}
  // onReady  onReady() {}
  // corresponds to onShow  componentDidShow() {}
  // corresponds to onHide  componentDidHide() {}
  // onPageScroll  onPageScroll() {}
  // onReachBottom  onReachBottom() {}
  render() {    return <View className="index" />  }}
export default Index

Functional Component

import React, { useEffect } from 'react'import { View } from '@binance/mp-components'import { useReady, useDidShow, useDidHide } from '@binance/mp-service'
function Index() {  // All React Hooks can be used  useEffect(() => {})
  // corresponds to onReady  useReady(() => {})
  // corresponds to onShow  useDidShow(() => {})
  // corresponds to onHide  useDidHide(() => {})
  // corresponds to onPageScroll  usePageScroll(() => {})
  // corresponds to onReachBottom  useReachBottom(() => {})
  return <View className="index" />}
export default Index

onTabItemTap#

Fired whenever tab item tapped

Parameters#

Object#
PropertyTypeDescription
indexStringthe index of the tab item starting from 0
pagePathStringthe path of the tab item
textStringthe text value of the tab item

Page Configuration#

For each page file (e.g. . /pages/index/index.jsx), we can add a new . /pages/index/index.config.js file for page configuration, and the default export of index.config.js is the page configuration.

// file: pages/index/index.config.jsexport default {  navigationBarTitleText: 'Home'}

Routing parameters#

In the page component, you can get the current page's routing parameters via getCurrentInstance().router.

import React, { Component } from 'react'import { View } from '@binance/mp-components'
class Index extends Component {  // It is recommended that the result of getCurrentInstance() be saved for later use when the page is initialized.  // instead of calling this API frequently  $instance = getCurrentInstance()
  componentDidMount() {    // Get the routing parameters    console.log($instance.router)  }
  render() {    return <View className="index" />  }}
export default Index

Lifecycle triggering mechanism#

React's lifecycle#

The lifecycle methods of React components are supported in mini program.

Trigger timing:

  1. componentWillMount ()

Triggered after onLoad, before the page component is rendered to BMP's virtual DOM.

  1. componentDidMount ()

Triggered after the page component is rendered to BMP's virtual DOM.

However, this does not mean that virtual DOM data has been transferred from the logical level setData to the view level. It can only be done during the onReady lifecycle.

Methods for mini program pages

The methods of the page can also be used: write the methods of the same name in the Class Component and use the corresponding Hooks in the Functional Component.

onLoad (options)#

Page routing parameters can be accessed during this lifecycle by calling getCurrentInstance().router.

onReady ()#

From this lifecycle mini program has already rendered DOM nodes to the rendering layer using APIs.

onReady for child components

The onReady lifecycle is only triggered for page components. Child components can listen to the onReady() lifecycle of a page component using mini program's built-in messaging mechanism.

A child component in a page

import React from 'react'import { View } from '@binance/mp-components'import { eventCenter, getCurrentInstance } from '@binance/mp-service'
class Test extends React.  $instance = getCurrentInstance()
  componentWillMount () {    const onReadyEventId = this.$instance.router.onReady    eventCenter.once(onReadyEventId, () => {      console.log('onReady')    })  }
  render () {    return (      <View id="only">      </View    )  }}

componentDidShow ()#

Triggered when the page is displayed/cut to the foreground.

onShow for child components

The onShow lifecycle is triggered only for page components. Child components can listen to the onShow() lifecycle of a page component using mini program's built-in messaging mechanism.

A child component in a page

import React from 'react'import { View } from '@binance/mp-components'import { eventCenter, getCurrentInstance } from '@binance/mp-service'
class Test extends React.Component {  $instance = getCurrentInstance()
  componentWillMount() {    const onShowEventId = this.$instance.router.onShow    // Listening    eventCenter.on(onShowEventId, this.onShow)  }
  componentWillUnmount() {    const onShowEventId = this.$instance.router.onShow    // Unload    eventCenter.off(onShowEventId, this.onShow)  }
  onShow = () => {    console.log('onShow')  }
  render() {    return <View id="only" />  }}

componentDidHide ()#

Triggered when the page is hidden/cut to the background.

onHide for child components

The onHide lifecycle is triggered only for page components. Child components can listen to the onHide() lifecycle of the page component using mini program's built-in messaging mechanism.

A child component in a page

import React from 'react'import { View } from '@binance/mp-components'import { eventCenter, getCurrentInstance } from '@binance/mp-service'
class Test extends React.Component {  $instance = getCurrentInstance()
  componentWillMount() {    const onHideEventId = this.$instance.router.onHide    // Listening    eventCenter.on(onHideEventId, this.onHide)  }
  componentWillUnmount() {    const onHideEventId = this.$instance.router.onHide    // Unload    eventCenter.off(onHideEventId, this.onHide)  }
  onHide = () => {    console.log('onHide')  }
  render() {    return <View id="only" />  }}

onPageScroll()#

Listens user swiping the page.

Parameter Object object:

PropertyTypeDescription
scrollTopNumberScroll distance in the vertical direction (unit: px)

Note: To reduce the impact of triggering of nonessential events on communication between the rendering layer and the logic layer, this method should be defined in page only when necessary. Do not define an empty method. Note: Avoid repeated execution of in onPageScroll that may trigger communication between the rendering layer and the logic layer. Transferring large volume of data each time will result in longer communication time.

A child component in a page

import React from 'react'import { View } from '@binance/mp-components'
class PageScroll extends React.Component {  onPageScroll(scrollTop) {    console.log('onPageScroll', scrollTop)  }
  render() {    return <View id="only" />  }}

onReachBottom()#

Listens user swiping up to the bottom of the page.

  • You can set the trigger distance onReachBottomDistance in the app.json window option or in the Page Configuration.
  • This event is only triggered once when the page scrolls within the trigger distance.

A child component in a page

import React from 'react'import { View } from '@binance/mp-components'
class ReachBottom extends React.Component {  onReachBottom() {    console.log('onPageReachBottom')  }
  render() {    return <View id="only" />  }}

onShareAppMessage(Object)#

Listen to the user click on the in-page share onbutton assembly open-type="share" Or the upper-right menu "Share" on behavior, or execute mpservice.showSharePanel, and customize the share content.

Parameters#

Object#
PropertyTypeDescription
fromStringShare the source of the event. button: In-page share button, menu: Retweet menu on top right, code: Execute mpservice.showSharePanel
targetStringif from The value is button, Then target That triggered this retweet. button, otherwise undefined

This event handler requires return One Object or Promise, used to customize the sharing content, returns the following:

fieldTypeIntroductionsDefault value
titleStringSharing TitleCurrent applet name
descStringDescription
imageUrlStringCustom picture path, should be network picture path. Support for PNG and JPG.Use default screenshots
pathFunctionSharing pathCurrent page path Must be based on / Full path to start
successFunctionCallback function when the user forwards on
import React, { Component } from 'react'import { View } from '@binance/mp-components'
class Index extends Component {  onShareAppMessage(...args) {    console.log('onShareAppMessage', args)    return Promise.resolve({      title: 'my title',      desc: 'mydesc',      imageUrl: 'https://public.bnbstatic.com/static/images/common/ogImage.jpg',      path: 'pages/extended/pages/share/share?p=1',      success: res => console.log('shareResult', res.shareResult)),    }  })
  render() {    return <View className="index" />  }}
export default Index