Jer*_*ner 4 toast react-native react-redux native-base
我在 React Native 应用程序中使用 NativeBase。我试图根据在 redux 操作中设置的错误显示 Toast 组件,因为它是通过调用 API 发生的。
它现在会显示,但目前我收到警告消息:
警告:无法在现有状态转换期间更新(例如在
render组件内部或其他组件的构造函数中)。Render 方法应该是 props 和 state 的纯函数;构造函数的副作用是一种反模式,但可以移至componentWillMount.
我不确定如何绑定它或我可以做些什么来解决警告。
渲染方法
render() {
return (
<View>
{this.renderError()}
{this.renderForm()}
</View>
);
}Run Code Online (Sandbox Code Playgroud)
渲染错误方法
renderError() {
if (this.props.error.type === 'server') {
return (
Toast.show({
text: this.props.error.message,
buttonText: 'Okay',
duration: 5000,
type: 'danger'
})
);
}
}Run Code Online (Sandbox Code Playgroud)
版本
反应本机: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
};Run Code Online (Sandbox Code Playgroud)
现在在我的行动中,我可以调用:
ToastService.showToast(data);Run Code Online (Sandbox Code Playgroud)
您可以创建一个函数并在外部调用该函数。但是请确保您的应用程序使用了 native-base 的 Root 组件。无需像您一样返回组件。调用这个函数会显示 toastr,现在你可以自由地从任何地方调用。但请确保 Root 组件包装您的应用程序。
从'native-base'导入{吐司};
export const toastr = {
showToast: (message, duration = 2500) => {
Toast.show({
text: message,
duration,
position: 'bottom',
textStyle: { textAlign: 'center' },
buttonText: 'Okay',
});
},
};
Run Code Online (Sandbox Code Playgroud)
现在在您的操作中,您可以调用 toastr 函数
toastr.showToast('Verication code send to your phone.');
或者在 redux 操作中
const signup = values => dispatch => {
try {
// your logic here
} catch (error) {
toastr.showToast(error.message)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7056 次 |
| 最近记录: |