remaxjs / remax

使用真正的 React 构建跨平台小程序
https://remaxjs.github.io/remax/
MIT License
4.57k stars 364 forks source link

[BUG] onShareAppMessage 无效问题 #1968

Closed FlynnZhouZz closed 1 year ago

FlynnZhouZz commented 1 year ago

bug 描述 在函数组件中使用onShareAppMessage 无效问题

复现步骤 核心代码

import { usePageEvent } from 'remax/macro';

export default (props) => {
    usePageEvent('onShareAppMessage', () => {
        return {
            title: '后浪成长计划',
            path: `/pages/index/index?from=share`,
        };
    });
    usePageEvent('onShareTimeline', () => { });
};

无效结果

image

在排查的时候,发现如下代码注释后是成功的

// babel.config.js
module.exports = {
    presets: [
        ['remax', {
            // 'react': { runtime: 'automatic' }, // 注释这一行打包后是会出现正常分享按钮
            'decorators': { legacy: true },
            'throw-if-namespace': true,
            'targets': ['chrome >= 49', 'firefox >= 64', 'ios >= 8', 'Android > 4.4'],
        }],
    ],
    plugins: [],
};

但此修改,整个小程序报如下错误 image

期望结果 期待onShareAppMessage、onShareTimeline能正常展示效果,对小程序进行分享和分享至朋友圈。

版本信息:

其他信息 [如截图等其他信息可以贴在这里]

watsonhaw5566 commented 1 year ago

我猜测你配置的 babel preset remax 覆盖了原有的 remax preset ,
remax 的 onShareAppMessage onShareTimeline 是正常运行的, 检查一下自己的 preset 配置。

image
FlynnZhouZz commented 1 year ago

我猜测你配置的 babel preset remax 覆盖了原有的 remax preset , remax 的 onShareAppMessage onShareTimeline 是正常运行的, 检查一下自己的 preset 配置。

image

image 我就是安装官网的例子配置的,我也不知道哪里出现问题了。我现在都无从下手了~

watsonhaw5566 commented 1 year ago

移除 babel 的配置,再跑一次

FlynnZhouZz commented 1 year ago

移除 babel 的配置,再跑一次

移除跑,报下面的错误了

image

watsonhaw5566 commented 1 year ago

先删除一下 babel.config.js ,删除 dist 目录,再跑一次。

FlynnZhouZz commented 1 year ago

经历了一整天的摸索(还是排除法最好用),问题终于得到解决了。感谢 @watsonhaw5566 兄弟的指导。

问题原因

导致我出现onShareAppMessage、onShareTimeline并不是官方库的问题,按照官方文档的使用方法是能够正常实现转发和分享至朋友圈功能的。 也不是babel.config.js的presets配置问题。

而我本地失败的原因是两个地方:

  1. 因为在编写组件的时候,有些组件没有引入import React from 'react';,即使你导入和reactReact还是必须要写;

    注意,是所有UI组件必须都要导入react

    
    // 正确导入
    import React from 'react';
    import React, { useEffect, useState } from 'react';

//错误导入 没有导入react import { useEffect, useState } from 'react';

2. 在我的`Container.js`组件中使用了`hideShareMenu()`方法获取页面路由,导致react运行失败。
```react
//Container关键代码
import { View, hideShareMenu } from 'remax/wechat';

...

const [path, setPath] = useState();
useEffect(() => {
    // eslint-disable-next-line no-undef
    const pages = getCurrentPages();
    if (pages && pages?.length > 0) {
        const path = pages?.[pages.length - 1]?.route;
        // 此行代码会产生「错误边界」问题,因此注释了
        // if (!canShare) hideShareMenu?.();
        setPath(path);
    }
}, []);

以上两个因素导致失败的本质原因是程序在运行时,遇到上诉两种错误,产生「错误边界」导致的。

react官方文档说明:React 的内部状态被破坏,并且在下一次渲染时 产生 可能无法追踪的 错误

所以我针对上面两个原因,调整代码后,程序就正常跑通了,开心~ 希望能够帮助到遇到同类问题的小伙伴~