以原生反应方式开展癌症治疗应用:
当前功能:当我移动滑块并更改应用程序上的日期时,它会成功地将更改发送到redux存储。不幸的是,我的UI没有更新,即使我从我要求发送的表示组件中调用相同的store
。
结果如下: GIF of redux store changing while UI is static
通过
打印store.getState();
store.subscribe(() =>
console.log(store.getState())
);
我尝试使用订阅,但似乎这不是正确的方法。想法?
我的代码片段(全部在一个小文件中,在下面链接)
动作
//action
function set_num_treatments(num) {
return {
type: SET_NUM_TREATMENTS,
num: num
}
}
设置标题
SET_NUM_TREATMENTS = "SET_NUM_TREATMENTS"
主减速机
function main_reducer(state = initialState, action) {
switch (action.type) {
case SET_PAGE_VIEW:
return Object.assign({}, state, {
current_page: action.page_of_interest
})
case SET_NUM_TREATMENTS:
return Object.assign({}, state, {
num_treatments: action.num
})
case SET_INTER_TREATMENT_INTERVAL:
return Object.assign({}, state, {
inter_treatment_interval: action.weeks_between_treatments
})
case SET_TREATMENT_START_DATE:
return Object.assign({}, state, {
treatment_start_date: action.date
})
default:
return state
}
return state
}
这是我开店的地方&产生打印功能
let store = createStore(main_reducer);
store.getState();
store.subscribe(() =>
console.log(store.getState())
);
这是表示组件
class TreatmentSettings extends React.Component {
constructor(props){
super(props)
}
render() {
const props = this.props
const {store} = props
const state = store.getState()
return(
<View style={styles.treatment_option_slider_card}>
<Text style={styles.my_font, styles.tx_settings_header}>{state.num_treatments} Treatments</Text>
<Slider step={1} minimumValue={1} maximumValue={20} value={12}
onValueChange={(num_treatments) => {store.dispatch(set_num_treatments(num_treatments))}} />
<Text style={styles.my_font, styles.tx_settings_header}>X Weeks Between Treatments</Text>
<Slider step={1} minimumValue={1} maximumValue={4} value={2} style={{marginBottom:60}}
onValueChange={(value) => {store.dispatch(set_inter_treatment_interval(value))}}
/>
</View>
)
}
}
最后两个组件包含应用程序的主要容器
export default class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Provider store={createStore(main_reducer)}>
<AppContainer />
</Provider>
);
}
}
class AppContainer extends React.Component {
constructor(props){
super(props)
}
render(){
return(
<View style={styles.container}>
<TreatmentSettings store={store} />
<Text>footertext</Text>
</View>
)
}
}
如果你想要全部看到,那么一个gist文件就在这里:https://github.com/briancohn/learning-redux/blob/navigation_addn/App.js 我非常感谢帮助 - 提前致谢! -Brian
答案 0 :(得分:3)
我认为您更新商店的方式很好但是组件如何监听更改有问题。
您似乎打算使用connect
中的react-redux
来容器连接到商店。然后,您可以使用mapStateToProps
从商店获取数据作为道具传递到组件中。例如,请检查https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options。