为什么按钮onClick功能有效?
为什么{this.test.bind(this)}不起作用?
如果单击按钮按钮,事件可以正常并跳回
{this.test.bind(this)}无法正常工作。
如果你使用{this.test()}它可以工作,但会有一些错误
Warning: setState(...): 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`.
import React, {Component, PropTypes} from "react";
import {browserHistory} from 'react-router';
import {connect} from "react-redux";
import * as authActions from "../../actions/auth";
import {LoginForm} from "../../components";
@connect(
state => ({
user: state.async.user,
userState: state.async.loadState && state.async.loadState.user
}),
authActions
)
class Login extends Component {
static propTypes = {
user: PropTypes.any,
userState: PropTypes.any,
login: PropTypes.func.isRequired,
};
test() {
browserHistory.push('/test');
}
render() {
const {user, userState, login} = this.props;
require('./Login.scss');
return (
<div>
<button type="button" onClick={this.test.bind(this)}>test</button>
{this.test.bind(this)}
<LoginForm onSubmit={login}/>
</div>
);
}
}
export default Login;
&#13;
答案 0 :(得分:0)
{this.test.bind(this)}
创建一个新函数,但实际上并没有执行该函数。
按钮有效,因为按下按钮时将执行onClick
功能。
this.test()
会抛出该警告,因为渲染将对任何组件执行多次。
如果您在组件安装时尝试导航到/test
,那么您应该使用React lifecycle method componentDidMount()
如果没有,则应从组件中删除{this.test.bind(this)}
。