您好,登錄后才能下訂單哦!
要在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。