我有两个react组件,即Dashboard和singleFeature。在Dashboard中,我有一个ionRangleSlider,它从redux状态中获取值。我正在仪表板中渲染singleFeature组件。SingleFeature组件创建一个获取网络请求,并使用dispatch方法更新redux状态。
位于Dashboard内的ionRangeSlider从redux状态中获取值,该状态由singleFeature组件更新。但不管我尝试了什么,它都没有反映出ionRangeSlider。然而,我可以看到redux状态正在更新,但没有反映在任何组件中。
代码:
Dashboard.js
<div id="slider"><IonRangeSlider ref={r => this.ionSlider = r}
skin={this.state.skin} values={this.state.values} /></div>
<SingleFeature name={this.state.name} id={this.state.id} user={this.state.user} />
componentDidUpdate(prevProps,prevState) {
if (this.props.dates !== prevProps.dates) {
console.log(`In update`)
this.ionSlider.update({ values: this.props.dates })
}
}
然后转到singleFeature并运行一个函数并更新redux状态。
singleFeature.js
fetch(`http://api/dates`)
.then(data => data.json())
.then(res => {
for(let i in res){
let dates = res[i]["dates"];
}
this.props.updateState(dates)
})
componentDidUpdate(prevProps,prevState) {
if (this.props.dates !== prevProps.dates) {
console.log(`In update`)
console.log(this.props.dates)
}
}
并且这两个组件由运行这些方法的react-redux
通过{connect}连接。
//fetch from redux store
const FetchFromStore = (state) => {
return {
dates: state.dates
}
}
//update redux store functions
const UpdateStore = (dispatch) => {
return {
updateState: (dates) => dispatch(
{
type: 'UPDATE_DATES',
payload: dates
})
}
}
以及还原文件
const stateActions = (state = initialState, action) => {
switch (action.type) {
case 'UPDATE_DATES':
state.dates = [...state.dates,...action.payload];
console.log(state.dates) //which is updating
return state;
}
return state;
}
componentdidUpdate
方法在状态更新后均不起作用。
感谢您的评论。看来我更新状态的方式不对。
//redux payload actions
const stateActions = (state = initialState, action) => {
switch (action.type) {
case 'UPDATE_DATES':
// state.dates = [...state.dates,...action.payload];
let dates_arr = [...state.dates];
state.dates = [...dates_arr,...action.payload]
return {...state}
}
return state;
}
它运行良好,正在更新所有组件。