【发布时间】:2019-02-28 07:06:44
【问题描述】:
我有三个页面,PageA、PageB 和 PageC,其中包含一个表单元素 formField。
globalReducer.js 中的状态
import { fromJS } from 'immutable';
const initialState = fromJS({
userInteractionBegun: false,
pageActive: '',
refreshData: true,
})
当组件(页面)安装并刷新formField 为空白时,我想调度一个将pageActive 设置为相应页面值(A、B 或 C 之一)的操作,如果@ 987654328@.
对于每个页面组件,要从 globalReducer 获取 props 中的 pageActive 状态,我愿意,
function PageA(props) {
//.....
}
// globalState is defined in conigureStore, I am using immutable.js. Link provided below this code.
const mapStateToProps = state => ({
pageActive: state.getIn(['globalState', 'pageActive']),
})
export default connect(mapStateToProps, null)(PageA);
store.js
import globalReducer from 'path/to/globalReducer';
const store = createStore(
combineReducers({
globalState: globalReducer,
//...other reducers
})
)
我想抽象逻辑以在每次组件(页面)挂载时更新pageActive。
我知道如何使用 HOC 抽象此逻辑,但我不知道如何使用 react hooks 来实现,因此每次 pageA、pageB 或 pageC 挂载时,都会执行一个操作如果userInteractionBegun 为假,则发送到setPageActive 并且formField 设置为空白。
例如,我会在 pageA.js
import usePageActive from 'path/to/usePageActive';
const [pageActive, setPageActive] = useReducer(props.pageActive);
usePageActive(pageActive);
然后在usePageActive.js
export default usePageActive(pageActive) {
const [state, setState] = useState(pageActive);
setState(// dispatch an action //)
}
【问题讨论】:
-
可以用效果吗? “如果你熟悉 React 类的生命周期方法,你可以把 useEffect Hook 想象成 componentDidMount、componentDidUpdate 和 componentWillUnmount 的组合。” -- reactjs.org/docs/hooks-effect.html
-
@richbai90 嗯,我要
usePageActive自定义效果。我不确定如何从那里分派一个动作。 -
抱歉,我一开始没有理解您的问题。我认为我的更新答案会对您有所帮助。
标签: javascript reactjs