繁体   English   中英

为什么道具在状态更新时不更新?

[英]Why aren't props updated as state is updated?

我正在将一个组件的状态传递给另一个组件作为道具。 当该状态正在更新时,似乎并没有在更新相应的道具。

我已经尝试了很多方法,例如将其放入return函数中并更新“低级”组件状态作为支持,但似乎没有任何效果。

这是构造函数

class Test extends Component{
    constructor(props){
        super(); 
        this.state = {
            testing:false,
            hitWall:false,
            outTime:false,
            outBounds:false,
            youWon:false

        }
        this.maze=[]
    }

这是状态更新的地方:

    attemptMaze = () => {
        this.setState({
            testing:true
        })
    }

这是我使用该事件侦听器构建事物的地方:

      return (
          <div className="holderDiv">
        <div onMouseOver={(this.state.testing) ? this.outOfBounds:undefined} className="outOfBounds"></div>
        <div onMouseOver={(this.state.testing) ? this.outOfBounds:undefined} className="outOfBoundsTwo"></div>
        <div onMouseOver={(this.state.testing) ? this.outOfBounds:undefined} className="outOfBoundsThree"></div>
        <form onSubmit={this.state.testing?this.handleSubmit:undefined}>
        <button onClick = {this.state.testing?this.submitMaze:this.didntStart} type="submit" className="finishMaze" style={{'display':this.state.submitShowing}}>Submit Maze</button>
        <div className="grid">
        {this.state.maze}
        </div>
        </form>

        <button type="submit" onClick={this.attemptMaze} className="startEndButton" style = {{'fontSize':'30px'}}>Attempt Maze</button>
        <h1 className="displayName">{this.state.name}</h1>
        <TimerTwo />
        </div>

这是我正在构建“下部”组件(正方形)的地方

getMaze = async (e) => {
        const mazeResponse = await fetch(`/maze/test/${this.props.match.params.testId}`)

        const parsedResponse = await mazeResponse.json();
        console.log(parsedResponse.data,'<----parsedResponse.data')
        testMaze = parsedResponse.data.maze;
        testName = parsedResponse.data.name
        console.log(testMaze)
        this.setState({
            name:testName,
            maze:
            testMaze.map((element)=>{
            return <div><Square hit ={this.hit} testing={this.state.testing} className="cell" color={element=="1"?'black':null} style={{'height':'5px','width':'5px','backgroundColor':element==1?'black':'white','margin':0}}></Square></div>
        }
        )
    })

    }

这是我渲染下部组件的地方

render(){
        return(
            <div className="boxes" onMouseOver = {this.props.testing?this.switchColor:undefined} style={{'height':'5px','width':'5px','backgroundColor':this.state.color,'margin':'0'}}>
            </div>
        )
    }

我似乎无法做到使switchColors在“ testing”为true时运行,而在“ testing”为false时不运行。 这是我似乎无法在该项目中管理的最后一个错误。 任何帮助表示赞赏。

  1. 尝试将button type="submit"替换为button type="button"以避免不必要的表单提交。

  2. 在所有事件处理程序中包括console.log语句,以确保它们被调用。 您可能对react事件属性或事件处理程序有错别字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM