因此,您希望在视图之间保留图像信息。 “视图”是指不同的 HTML 页面吗?我想一个更标准的做事方式是:
- 将文件内容/路径存储在某个状态(例如 redux 状态)
- 使用客户端路由器(例如 react-router)在保持状态的同时更改视图
如果你从未使用过客户端路由,它看起来像这样(使用 react-router):
import { Router, Route, browserHistory } from 'react-router'
// Iy you use redux to handle the state
import { createStore } from 'redux'
import myReducer from 'my-reducer'
const store = createStore(myReducer)
const history = syncHistoryWithStore(browserHistory, store)
// Your view components
function Top(props) { ... }
function UploadImage(props) { ... }
function EditImage(props) { ... }
// The Router itself
ReactDOM.render(
<Router history={history}>
<Route path="/" component={Top} >
<Route path="upload-image" component={UploadImage} />
<Route path="edit-image" component={EditImage} />
</Route>
</Router>)
如果你之前没用过redux,可以这样使用:
首先,创建reducer
import { combineReducers } from 'redux'
const myReducer = combineReducers({ imagePath })
// This is called a reducer function
function imagePath(oldState = "", action) {
switch(action.type) {
case 'SET_PATH':
return action.payload
}
}
接下来,连接您的组件以获取状态值(例如 UploadImage)
const ReduxUploadImage = connect(function(state) {
return {
imagePath: state.imagePath
}
})(UploadImage)
现在,如果您使用ReduxUploadImage 而不是UploadImage,则可以通过props.imagePath 访问imagePath。 connect 函数还会为你的 props 添加一个 dispatch 函数。
最后,您可以通过在组件中调用来设置路径(但不是渲染函数本身:这将是一个anti-pattern)
props.dispatch( { type: 'SET_PATH', payload: "the_path" } )
最后,使用dedicated middleware可以很容易地保持页面之间的redux状态或刷新。