Javascript 状态更新可能是异步的,这到底是什么.props?
以上是我的应用程序中的数据状态:Javascript 状态更新可能是异步的,这到底是什么.props?,javascript,reactjs,Javascript,Reactjs,以上是我的应用程序中的数据状态: state = { persons:[ {id:"cbhc", name:"surya",age:26,sex:"male"}, {id:"rgt", name:"sachin",age:36,sex:"male"}, {id:"cbcchc", name:"rahul",age:46,sex:"male"} ], showdetails:false, **counter:0**, }; 要修复它,请使用第二种形式的
state = {
persons:[
{id:"cbhc", name:"surya",age:26,sex:"male"},
{id:"rgt", name:"sachin",age:36,sex:"male"},
{id:"cbcchc", name:"rahul",age:46,sex:"male"}
],
showdetails:false,
**counter:0**,
};
要修复它,请使用第二种形式的setState()
,它接受函数而不是对象。该函数将接收前一个状态作为第一个参数,应用更新时的道具作为第二个参数:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
这里到底是什么:props.increment
我的代码:
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
我想知道什么是道具.increment
我的组件框架:
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
一旦我更改输入框中的文本,我的计数器应该会更新,但它返回NaN,为什么????
请参阅下面附带的屏幕截图
但是如果我改变下面的代码
updateStudentHandler = id => event => {
//debugger;
const studentIndex = this.state.details.findIndex(d => d.id === id);
console.log(studentIndex);
let duplicate = {
...this.state.details[studentIndex]
};
duplicate.name = event.target.value;
const dd = [...this.state.details];
dd[studentIndex] = duplicate;
this.setState({
details: dd
});
this.setState((referencetoprevState, Props) => {
return {
counter: referencetoprevState.counter + Props.increment
};
});
};
使用值(9000)而不是道具。增量会按预期更新计数器值
this.setState((state, props) => {
return { counter: state.counter + props.increment };
});
为什么我需要显式地提供值,而不仅仅是像props.increment类似于state.counter,因为state.counter将其值从上一个状态取为0,而props.increment不从用户定义组件的jsx的increment={1}取值1,该组件是Studentinfocomp??
任何限制/原因???如React文档所述: 当React看到表示用户定义组件的元素时,它将JSX属性作为单个对象传递给该组件。我们称这个物体为“道具” 我建议进一步阅读官方文件,特别是其中的部分 另外,
setState()
this.setState((state, props) => {
return { counter: state.counter + 9000 };
});
更新程序函数收到的状态和道具都保证是最新的。更新程序的输出与状态进行了浅层合并
总之:
基本上,您在代码中使用的是函数的updater参数,它包含两个参数,state
和props
:
状态
:是对应用更改时组件状态(如上所述)的引用props
:组件的当前属性我希望这有帮助 是的,我得到了,就像在状态中为对象设置值一样,我们在元素标记(jsx)中为道具提供了值,因此从我上面的代码中我发现了一些东西 根据我的理解,我相信setState的updater函数有两个参数,它们基本上是按顺序排列的,因为第一个参数是前一个状态,第二个是组件的当前属性。 在这里,我的主要组件和所有其他子组件一起呈现在页面上。 所以,props.increment来自Appl,它扩展了“react”中的组件 从我的骨骼和骨骼体中移除增量道具,即从Singlestudent和Studentinfocomps中移除增量道具 因此,最后:
this.setState((state, props) => {
return {counter: state.counter + props.step};
});
将是:
this.setState((referencetoprevState, Props) => {
return {
counter: referencetoprevState.counter + Props.increment
};
});
道具是传递给组件的内容:
,您不是有意使用此.state.increment吗?的可能副本请参阅我编辑的代码并提供有价值的输入
this.setState((state, props) => {
return { counter: state.counter + 9000 };
});
this.setState((state, props) => {
return {counter: state.counter + props.step};
});
this.setState((referencetoprevState, Props) => {
return {
counter: referencetoprevState.counter + Props.increment
};
});
this.setState((referencetoprevState, Props) => {
return {
counter: referencetoprevState.counter + 1
};
});