使用 Native Base Toast 显示来自 Redux Action 的错误

Use Native Base Toast To Show Error From Redux Action

我在 React Native 应用程序中使用 NativeBase。我正在尝试根据在 redux 操作中设置的错误显示 Toast 组件,因为它是通过调用 API.

发生的

现在会显示,但目前我收到警告消息:

Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

我不确定如何绑定它或如何解决警告。

渲染方法

render() {
  return (
    <View>
      {this.renderError()}
      {this.renderForm()}
    </View>
  );
}

渲染错误方法

renderError() {
  if (this.props.error.type === 'server') {
    return (
      Toast.show({
        text: this.props.error.message,
        buttonText: 'Okay',
        duration: 5000,
        type: 'danger'
      })
    );
  }
}

版本

React Native:0.55.4

本机基础:2.4.5

编辑:为清楚起见添加示例

我需要根据服务器的响应显示一个 Toast。例如,如果用户名和密码与帐户不匹配,我需要渲染 Toast。

解法:

我最终创建了一个 ToastService:

import { Toast } from 'native-base';

function showToast(message) {
  return (
    Toast.show({
      text: message,
      buttonText: 'Okay',
      duration: 5000,
      type: 'danger'
    })
  );
}

export default {
  showToast
};

现在在我的操作中我可以调用:

ToastService.showToast(data);

检查此实现的 React Native Seed https://reactnativeseed.com/

您可以创建一个函数并在外部调用它。但是请确保您的应用程序使用 native-base 的 Root 组件进行包装。无需像您一样 return 一个组件。调用此函数将显示 toastr,现在您可以自由地从任何地方调用。但请确保 Root 组件包装您的应用程序。

从 'native-base' 导入 {Toast};

export const toastr = {
  showToast: (message, duration = 2500) => {
    Toast.show({
      text: message,
      duration,
      position: 'bottom',
      textStyle: { textAlign: 'center' },
      buttonText: 'Okay',
    });
  },
};

现在在你的动作中你可以调用 toastr 函数

toastr.showToast('Verication code send to your phone.');

或者在 redux 操作中

const signup = values => dispatch => {
  try {
    // your logic here


  } catch (error) {
    toastr.showToast(error.message)
  }
}

我使用 React Hooks 解决了这个问题。

() => {
       useEffect(() => {
           if(error) {
               Toast.show({
                   text: this.props.error.message,
                   buttonText: 'Okay',
                   duration: 5000,
                   type: 'danger'
               })
            }
        })

        return (
            <View>
                {this.renderForm()}
            </View>
        );
    }

正如 Dwayne 上面所说,您需要使用 useEffect 以便在渲染周期之前调用 Toast。你可以像这样包装这个组件:

const ErrorToast: React.FC = () => {
    const {state} = useCollections();
    useEffect(() => {
        if(state.errored) {
            Toast.show({
                text: 'Oops. There has been an error',
                duration: 2000
            });
        }
    });

    return null;
}

然后简单地将其包含为 <ErrorToast />