gpt4 book ai didi

reactjs - 在单独的文件中 react 路由器代码

转载 作者:行者123 更新时间:2023-12-03 13:28:19 26 4
gpt4 key购买 nike

我是reactjs新手,正在努力学习react router的redux。我想将路线作为单独的文件。然而不知何故它不起作用,因为我无法传递依赖项。以下是代码详细信息。

工作index.js也有路由:

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from 'react-redux';
import {ReduxRouter} from "redux-react-router";
import {Route} from "react-router"

import createBrowserHistory from "history/lib/createBrowserHistory"
import configureStore from './store';

import App from "./containers/App";
import Home from "./components/Home";
import Countries from "./components/Countries";
import {fetchData} from './actions/actions';

const history = new createBrowserHistory();
const store = configureStore();

function loadData() {
store.dispatch(fetchData('https://restcountries.eu/rest/v1/all'))
}

ReactDOM.render(
<Provider store={store}>
<ReduxRouter>
<Route history={history}>
<Route component={App}>
<Route path='/' component={Home} />
<Route path='/countries' component={Countries} onEnter={loadData} />
</Route>
</Route>
</ReduxRouter>
</Provider>,
document.getElementById('root')
);

以下是我尝试拆分为单独的routes.js的代码

index.js

import 'babel-core/polyfill';
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from 'react-redux';
import {ReduxRouter} from "redux-react-router";
import {Route} from "react-router"

import createBrowserHistory from "history/lib/createBrowserHistory"
import configureStore from './store';

import routes from "./routes";
import {fetchData} from './actions/actions';

const history = new createBrowserHistory();
const store = configureStore();

ReactDOM.render(
<Provider store={store}>
<ReduxRouter>
<Route history={history} routes={routes}>
</Route>
</ReduxRouter>
</Provider>,
document.getElementById('root')
);

routes.js

import React from "react";
import { Provider } from 'react-redux';
import {ReduxRouter} from "redux-react-router";
import {Route} from "react-router"


import App from "./../containers/App";
import Home from "./../components/Home";
import Countries from "./../components/Countries";

const router =
<Route history={history}>
<Route component={App}>
<Route path='/' component={Home} />
<Route path='/countries' component={Countries} onEnter={loadData} />
</Route>
</Route>;

export default router;

但是它会抛出错误,因为无法识别 loadData 函数。

请帮忙。

最佳答案

将其作为子级传递,注意父级称为Router:

<Router history={history}>
{routes}
</Router>

此外,Route 不采用历史记录属性,Router 则采用。

在我的启动器上查看 Router.js 和 Route.js 的示例:https://github.com/DominicTobias/universal-react/tree/master/app

关于reactjs - 在单独的文件中 react 路由器代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36590202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com