要在React应用中与React Router一起使用Redux进行状态管理,可以按照以下步骤进行:
npm install react-router-dom redux react-redux
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from './reducers'; // 导入根reducer
import App from './App';
const store = createStore(rootReducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
// reducers/index.js
import { combineReducers } from 'redux';
import someReducer from './someReducer';
const rootReducer = combineReducers({
someReducer
});
export default rootReducer;
import React from 'react';
import { connect } from 'react-redux';
const SomeComponent = ({ someState }) => {
return (
<div>
{someState}
</div>
);
};
const mapStateToProps = state => ({
someState: state.someReducer.someState
});
export default connect(mapStateToProps)(SomeComponent);
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import SomeComponent from './SomeComponent';
const App = () => {
return (
<Router>
<Switch>
<Route path="/some-route" component={SomeComponent} />
</Switch>
</Router>
);
};
export default App;
通过以上步骤,就可以在React应用中使用React Router和Redux进行状态管理。在需要访问Redux store中状态的组件中,通过connect函数连接到store,从而实现状态管理。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。