重新呈现状态改变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我缺少什么?
您正在使用的渲染方法父组件的状态?我没有看到它被使用。 –