我有index.js 从那里获取路线 根 。 我需要访问商店并获得变量导航 登录后需要成立 并且最初是假的
import React from "react";
import ReactDOM from "react-dom";
import { HashRouter, Route, Switch } from "react-router-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import ReduxThunk from "redux-thunk";
import allReducers from "./Reducers";
import Root from "./root";
const store = createStore(allReducers, {}, applyMiddleware(ReduxThunk));
const loggedin = true;
ReactDOM.render(<Root store={store} />, document.getElementById("root"));
root.js文件是:
import React from "react";
import PropTypes from "prop-types";
import { Provider } from "react-redux";
import { HashRouter, Route, Switch } from "react-router-dom";
import Full from "./containers/Full/";
import { connect } from "react-redux";
// Views
import Login from "./views/Pages/Login/";
import Register from "./views/Pages/Register/";
import Page404 from "./views/Pages/Page404/";
import Page500 from "./views/Pages/Page500/";
const Root = ({ store }) => (
<Provider store={store}>
<HashRouter>
<Switch>
{/* <Route
exact="exact"
path="/login"
name="Login Page"
component={Login}
/> */}
<Route
exact="exact"
path="/register"
name="Register Page"
component={Register}
/>
<Route exact="exact" path="/404" name="Page 404" component={Page404} />
<Route exact="exact" path="/500" name="Page 500" component={Page500} />
{/* <Route path="/" name="Home" component={Full} /> */}
<Route
path="/"
render={() =>
this.props.navigate ? (
<Route component={login} />
) : (
<Route component={Full} />
)
}
/>
</Switch>
</HashRouter>
</Provider>
);
Root.propTypes = {
store: PropTypes.object.isRequired
};
const mapStateToProps = ({ authRed }) => {
const { navigate } = authRed;
console.log("navigation system ready:", navigate);
return { navigate };
};
export default connect(mapStateToProps, {})(Root);
我的控制台在mapstate登录到道具我返回了确切需要的数据 但如果我使用this.props.navigate错误发生 无法读取未定义的属性“道具”
有没有人有解决方案?
答案 0 :(得分:2)
您的根组件是functional component
且没有this
关键字,您需要destructure
道具并使用它,就像您store
const Root = ({ store, navigate }) => (
<Provider store={store}>
<HashRouter>
<Switch>
{/* <Route
exact="exact"
path="/login"
name="Login Page"
component={Login}
/> */}
<Route
exact="exact"
path="/register"
name="Register Page"
component={Register}
/>
<Route exact="exact" path="/404" name="Page 404" component={Page404} />
<Route exact="exact" path="/500" name="Page 500" component={Page500} />
{/* <Route path="/" name="Home" component={Full} /> */}
<Route
path="/"
render={() =>
navigate ? (
<Route component={login} />
) : (
<Route component={Full} />
)
}
/>
</Switch>
</HashRouter>
</Provider>
);