在Redux中,要将Redux存储发送给客户端,可以通过以下步骤实现:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers'; // 导入根Reducer
import App from './App';
const store = createStore(rootReducer); // 创建Redux存储
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
import React from 'react';
import { connect } from 'react-redux';
const MyComponent = ({ reduxState }) => {
// 在这里使用Redux存储的状态
return (
<div>
<h1>{reduxState.title}</h1>
{/* 其他组件内容 */}
</div>
);
};
const mapStateToProps = (state) => {
return {
reduxState: state // 将整个Redux存储映射到组件的props中
};
};
export default connect(mapStateToProps)(MyComponent);
import express from 'express';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers'; // 导入根Reducer
import App from './App';
const app = express();
app.get('/', (req, res) => {
const store = createStore(rootReducer); // 创建Redux存储
const appMarkup = renderToString(
<Provider store={store}>
<App />
</Provider>
);
const initialReduxState = store.getState(); // 获取Redux存储的状态
res.send(`
<html>
<head>
<title>My App</title>
</head>
<body>
<div id="root">${appMarkup}</div>
<script>
// 将Redux存储的状态作为初始数据传递给客户端
window.__INITIAL_REDUX_STATE__ = ${JSON.stringify(initialReduxState)}
</script>
<script src="client.js"></script>
</body>
</html>
`);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers'; // 导入根Reducer
import App from './App';
const initialState = window.__INITIAL_REDUX_STATE__; // 获取服务器端传递的初始Redux存储状态
const store = createStore(rootReducer, initialState); // 使用初始状态创建Redux存储
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
通过以上步骤,你可以在Redux中路由时将Redux存储发送给客户端,并在客户端上使用相同的Redux存储状态。这样可以确保在客户端上进行路由切换时,Redux存储的状态保持一致,从而实现数据的持久化和同步。
领取专属 10元无门槛券
手把手带您无忧上云