Javascript 让函数返回它';s每次更改的结果都会作出反应(在js中使用类似指针的影响)
我来自一个有着指点和荣耀的背景,所以这是我很难理解的 如果我在react中有一个类:Javascript 让函数返回它';s每次更改的结果都会作出反应(在js中使用类似指针的影响),javascript,reactjs,Javascript,Reactjs,我来自一个有着指点和荣耀的背景,所以这是我很难理解的 如果我在react中有一个类: import ComplexMathFunction from 'ComplexMathFunction.js'; export default class DisplayArray extends React.Component { constructor(){ super(); this.state = { gird : SomeGrid // someGrid is a 5 x
import ComplexMathFunction from 'ComplexMathFunction.js';
export default class DisplayArray extends React.Component {
constructor(){
super();
this.state = {
gird : SomeGrid // someGrid is a 5 x 5 array
}
}
componentDidUpdate(prevProps, prevState) {
if (this.props.doMath !== prevProps.doMath) {
this.AdjustGrid();
}
}
AdjustGrid = () => {
let tmpGrid = ComplexMathFunction(this.state.grid);
this.setState({ grid: tmpGrid)}
}
render (
return (
// display the grid within state
)
}
其中,ComplexMathFunction
只不过是一个循环,它获取值,计算每个网格元素,并为每个元素提供解决方案,直到网格完成
DisplayArray
检测它是否必须调用一个数学函数,在这个函数中,我怎样才能在数学函数的每个循环中让它返回并将其设置为状态?在我以前的编程经验中,我可以传递一个指针,函数将在其中更改值,在这种情况下,它将被呈现
但javascript/react中并非如此。我可以将整个
ComplexMathFunction
放在这个DisplayGrid
中,但这似乎是一个糟糕的做法 您可以尝试使用refs
:
class DisplayArray extends React.Component {
AdjustGrid = () => {
}
render (
return (
// display the grid within state
)
}
class Parent extends React.Component {
render() {
return <div>
<button onClick={() => this.displayArray.AdjustGrid()}>compute</button>
<DisplayArray ref={d => this.displayArray = d}/>
</div>
}
}
类DisplayArray扩展了React.Component{
调整网格=()=>{
}
渲染(
返回(
//显示状态中的栅格
)
}
类父类扩展了React.Component{
render(){
返回
这个.displayArray.AdjustGrid()}>compute
this.displayArray=d}/>
}
}