以下功能用于在使用react-router呈现路由之前检查用户是否已获得授权。我从忘了的地方得到了基本代码。
当我对本地存储进行简单的同步检查时,这工作正常,但是当我向服务器引入Axios调用时,事情变得很乱。
我在类似问题上阅读了很多SO的问题,即承诺没有返回值,我似乎修改了我的代码以符合常规陷阱。
我特别使用this question的最后一个答案来修复我的设置,但问题仍然存在。
在下面的代码中,console.logs正确输出参数,这意味着与return语句相关的失败。
具体错误是:
错误:AuthRoute(...):渲染没有返回任何内容。这通常意味着缺少return语句。或者,为了不渲染,返回null。
var totalAmount = 0;
$('.quantity, .price').keyup(function() {
totalAmount = 0;
var netAmount = 0;
var discount = 0;
$(".amount-row").each(function(index, row) {
var quantity = $(row).find('.quantity').val();
var price = $(row).find('.price').val();
var amount = quantity * price;
$(row).find('.amount').val(amount);
totalAmount += amount;
});
netAmount = totalAmount;
discount = $("#discount").val();
if (discount) {
netAmount = totalAmount - discount;
}
$("#total-amount").html(totalAmount)
$("#net-amount").html(netAmount)
});
$("#discount").keyup(function() {
var discount = $("#discount").val();
$("#net-amount").html(totalAmount - discount);
});
答案 0 :(得分:0)
在上面的评论之后,这对我有用。有必要创建一个单独的组件类。它不是非常优雅,但有效。
需要将代码放入componentWillReceiveProps()中,以便在每个新道具上进行更新。我知道componentWillReceiveProps()已被弃用。我将分开处理。
/auth/auth.js
import React from 'react';
import RenderRoute from './components/render_route';
const AuthRoute = ({component, ...props}) => {
let propsAll = {...props}
return (
<RenderRoute info={component} propsAll={propsAll} />
)
}
export default AuthRoute;
/auth/components/render_route.js
import React from 'react';
import PropTypes from 'prop-types';
import { Redirect, Route } from 'react-router-dom';
import axios from 'axios';
const PRIVATE_ROOT = '/account';
const PUBLIC_ROOT = '/';
class RenderRoute extends React.Component {
constructor (props) {
super(props);
this.state = {
route: ''
}
}
componentWillReceiveProps(nextProps, prevState){
const { isPrivate } = this.props.info;
let last_active_client = localStorage.getItem('last_active') ? localStorage.getItem('last_active') : 0;
let data = {
last_active_client: last_active_client
}
axios.post('/api-session', data).then(response => {
let isLogged = response.data.is_logged;
if(response.data.is_logged) {
// set last activity on local storage
let now = new Date();
now = parseInt(now.getTime() / 1000);
localStorage.setItem('last_active', now );
this.setState({ route: isPrivate
? <Route { ...this.props.propsAll } component={ this.props.info } />
: <Route { ...this.props.propsAll } component={ this.props.info } />
})
} else {
this.setState({ route: isPrivate
? <Redirect to={ PUBLIC_ROOT } />
: <Route { ...this.props.propsAll } component={ this.props.info } />
})
}
}).catch((error) => {
console.log(error);
});
}
render() {
return (
<div>
{this.state.route}
</div>
)
}
}
export default RenderRoute;