【发布时间】:2021-10-08 10:29:14
【问题描述】:
我有一个扫描二维码的二维码应用程序,它可以工作。我想在扫描成功后添加重定向操作。
这是我的代码
import React, {Component} from "react";
import ReactDOM from 'react-dom';
import { Redirect } from "react-router-dom";
import BarcodeScannerComponent from "react-qr-barcode-scanner";
class QR extends Component {
constructor(props) {
super(props);
this.state = {
data: "Not Found"
};
}
render() {
return (
<>
<BarcodeScannerComponent
width={500}
height={500}
onUpdate={(err, result) => {
if (result) {
this.setState({data: result.text});
return <Redirect to={this.state.data} />
}
else this.setState({data: "Not Found"});
}}
/>
<p>{this.state.data}</p>
</>
);
}
}
ReactDOM.render(
<QR />,
document.getElementById('qr-id')
);
虽然在成功扫描后,不会发生重定向。有人可以指出在反应中进行重定向的好方法吗?
【问题讨论】:
-
使用其他方式重定向(
const history = useHistory();和history.push(url);)或有条件地渲染它:{this.state.data !== "Not Found" && <Redirect to={this.state.data} />},而不是在事件处理程序中返回它(这绝对什么都不做) -
我有条件地渲染了虽然不知道为什么我得到一个错误“不变失败”,
{this.state.data !==Not Found ? ( <Redirect to={this.state.data} /> ) : (<p>{this.state.data}</p> )}
标签: javascript reactjs redirect react-router