重新呈現狀態改變DOM我看到這個post,但不知道如何在我的案件,不適用。基本上我有3-4輸入範圍欄,如果用戶更改任何滑塊其他2/3滑塊自動更改。我從後端獲得的初始值。之後,我已經爲我的狀態添加了初始值。爲我寫了這樣的代碼如何通過其他組件
我父組件
constructor(props){
super(props);
this.state ={
objectiveData:[]
}
var {objectiveData} = this.state;
this.props.objective_value.map((data,index) =>{
var newObj ={};
newObj['url'] = data.url;
newObj['name'] = data.name;
newObj['value'] = data.value;
newObj['pk'] = data.pk;
objectiveData[index] = newObj;
})
console.log("lcal",objectiveData)
this.setState({objectiveData});
}
updateValue = (obj) =>{
var {objectiveData} = this.state;
var selectedData = objectiveData.filter((data) => data.pk === obj.pk);
var diff=obj.value - selectedData[0].value;
var otherData = objectiveData.filter((data) => data.pk !== obj.pk);
var sum = otherData.map((data) =>(data.value)).reduce((a,b) => a + b,0);
console.log("sum",sum);
if(diff > 0){
for(var i=0;i < objectiveData.length;i++){
if(objectiveData[i].pk !== obj.pk){
console.log("object before value",objectiveData[i].value)
objectiveData[i].value = objectiveData[i].value - (objectiveData[i].value/sum);
console.log("object after value",objectiveData[i].value)
}else{
objectiveData[i].value = obj.value;
}
}
}else if(diff <0){
for(var i=0;i < objectiveData.length;i++){
if(objectiveData[i].pk !== obj.pk){
console.log("object before value plus",objectiveData[i].value)
objectiveData[i].value = objectiveData[i].value + (objectiveData[i].value/sum);
console.log("object before value minus",objectiveData[i].value)
}else{
objectiveData[i].value = obj.value;
}
}
}
return this.setState({objectiveData});
}
<MyInputRange maxValue={1} minValue={0} step={0.01}
updateProgramObjectiveValue={(value) => this.props.updateProgramObjectiveValue(value)}
value={data.value} objective_name={data.objective_name}
value_type={data.value_type} url={data.url} pk={data.pk}
updateValueLocally={this.updateValue.bind(this)}/>
這裏是我的子組件
updateObjectiveValues = (value) =>{
this.props.updateValueLocally({"value":value,"pk":this.props.pk})
}
render(){
return(
<InputRange
maxValue={this.props.maxValue}
minValue={this.props.minValue}
step={this.props.step}
value={this.state.value}
onChange={this.updateObjectiveValues.bind(this)}
/>
)
}
但我滑不動任何地方,甚至滑塊用戶moves.so請讓我知道應該如何迴應我的組件?基本上反應應該重新呈現每當setState調用。所以我在這裏被寵壞了? 編輯1:根據克里斯的回答 我說像這樣
this.setState({objectiveData});
this.forceUpdate();
但是,沒有luck..am我缺少什麼?
您正在使用的渲染方法父組件的狀態?我沒有看到它被使用。 –