这是我的代码
index.js
import React from "react";
import ReactDOM from "react-dom";
import { Route, BrowserRouter } from "react-router-dom";
import Main from "./Main";
import registerServiceWorker from "./registerServiceWorker";
ReactDOM.render(
<BrowserRouter>
<Route exact path="/" component={Main} />
</BrowserRouter>,
document.getElementById("root")
);
registerServiceWorker();
主.js
import React from "react";
import SelectList from "./SelectList";
class Main extends React.Component {
state = {
currentUser: "hello"
};
componentDidMount = () => {
console.log("Main", this.props);
};
render() {
return (
<div>
<h1>Hello world</h1>
<SelectList
currentUser={this.state.currentUser}
/>
</div>
);
}
}
export default Main;
选择列表.js
import React, { Component } from "react";
import { Route, Switch, withRouter } from "react-router-dom";
import Welcome from "./Welcome";
import LoginForm from "./LoginForm";
class SelectList extends Component {
componentDidMount = () => {
console.log("SelectList", this.props);
if (this.props.currentUser) {
this.props.history.push({ pathname: "/welcome" });
} else {
this.props.history.push({ pathname: "/login" });
}
};
render() {
return (
<div>
<Switch>
<Route exact path="/welcome" component={Welcome} />
<Route exact path="/login" component={LoginForm} />
</Switch>
</div>
);
}
}
export default withRouter(SelectList);
欢迎.js
import React, { Component } from "react";
class Welcome extends Component {
render() {
return <p>Welcome</p>;
}
}
export default Welcome;
登录表单.js
import React, { Component } from "react";
class LoginForm extends Component {
state = {
emailOrMobile: "",
password: ""
};
submitForm = () => {
console.log("submit form");
};
componentDidMount = () => {
console.log("hello world");
};
render() {
return (
<div>
<form>
Email or Mobile: <input type="text" /> <br />
Password: <input type="password" /> <br />
<input type="button" onClick={this.submitForm} />
</form>
</div>
);
}
}
export default LoginForm;
这里既没有Welcome.js
也没有LoginForm.js
得到渲染。我不知道我的代码有什么问题。根据selection.js
任一组件的渲染功能LoginForm.js
或Welcome.js
必须渲染。在这里,我也在Main.js
. 如果我将替换为componenetDidMunt
incomponentWillMount
那么SelectList.js
它也不起作用。另请参阅我电脑上行为的屏幕截图。