我正在使用功能组件并尝试实现MVVM。我想在不使用 useSelector hook 的情况下获取 redux 状态的更新值
这是我的代码
模型.js
export class Model {
getData = () => {
return store.getState().mReducer.jsonData
}
setData = (data) => {
store.dispatch(setData(data)) // storing in redux for further use
}
}
ViewModel.js
export class ViewModel {
onChangeTextHandler = (text) => {
this.model.setData(tmp)
}
}
View.js
export const View = () => {
const vm = useMemo(() => new ENReceivingViewModel(), [])
const model = useMemo(() => new ENREceivingModel(), []);
//IF I use this line then rerender happens otherwise nothing happens
//const { selectedOption, jsonData } = useSelector(state => state.ReceivingReducer)
return (
<TextInput value = {model.getData()[0]}
onChangeText={vm.onChangeTextHandler} />
)}
我认为不可能以这种方式处理它,模型对象保留初始化时存储的唯一值。
我认为将存储传递给类的方法将实现你想要的:
像这样:
export class Model {
getData = (store) => {
return store.getState().mReducer.jsonData
}
setData = (data) => {
store.dispatch(setData(data)) // storing in redux for further use
}
}
在组件中:
import store from "./store"
<TextInput value = {model.getData(store)[0]}
onChangeText={vm.onChangeTextHandler} />
或者另一种方法是在 useMemo 中添加依赖项
像这样:
const model = useMemo(() => new ENREceivingModel(), [someState]);
这样,每当 someState 发生变化时,新的 ENREceivingModel 就会替换之前的 ENREceivingModel