反应setState重新渲染

时间:2018-11-08 11:18:48

标签: javascript reactjs

首先,我真的是React的新手,所以请原谅我对主题的知识不足。

据我所知,当setState一个新值时,它将再次呈现视图(或需要重新呈现的部分视图)。

我有这样的事情,我想知道这是否是一个好习惯,如何解决此类问题以进行改进等。

class MyComponent extends Component {
    constructor(props) {
        super(props)
        this.state = { 
            key: value
        }
        this.functionRender = this.functionRender.bind(this)
        this.changeValue = this.changeValue.bind(this)
    }
    functionRender = () => {
        if(someParams !== null) {
            return <AnotherComponent param={this.state.key} />
        }
        else {
            return "<span>Loading</span>"
        }
    }
    changeValue = (newValue) => {
        this.setState({
            key: newValue
        })
    }
    render() {
        return (<div>... {this.functionRender()} ... <span onClick={() => this.changeValue(otherValue)}>Click me</span></div>)
    }
}

另一个组件

class AnotherComponent extends Component {
    constructor (props) {
        super(props)
    }
    render () {
        return (
            if (this.props.param === someOptions) {
                return <div>Options 1</div>
            } else {
                return <div>Options 2</div>
            }
        )
    }
}

该代码的目的是,当我单击范围时,它将更改状态键,然后<AnotherComponent />组件将因其参数而更改。

我保证当我设置setState时,在回调函数上我会抛出一个带有新值的控制台日志,并且它的设置正确,但是AnotherComponent不会更新,因为取决于给出的参数一件事或另一件事。

也许我需要使用MyComponent的某些生命周期?

修改

我发现param收到的AnotherComponent并没有改变,总是一样。

2 个答案:

答案 0 :(得分:1)

我建议您首先在console.log函数上使用简单的changeValue在父级中对其进行测试:

changeValue = (newValue) => {
    console.log('newValue before', newValue);
    this.setState({
        key: newValue
    }, ()=> console.log('newValue after', this.state.key))
}

setState可以接受callback,该状态将在状态实际更改后被调用(请记住setState is async)

因为我们看不到整个组件,所以很难理解那里到底发生了什么。 我怀疑newValue参数始终是相同的,但我不确定。
似乎您在props的构造函数中缺少AnotherComponent。应该是:

 constructor (props) {
    super(props) // here
}

尝试将if语句替换为:

{this.props.param === someOptions? <div>Options 1</div>: <div>Options 2</div>}

还添加此功能,以查看新道具是否真正到达组件:

componentWillReceiveProps(newProps){
    console.log(newProps);
}

并检查paramsomeOptions的类型,因为您(正确地)使用了===比较。

答案 1 :(得分:0)

首先,使用大箭头(=>)自动绑定方法,因此您无需在构造函数中进行绑定,如果更改组件的键,则第二次重新渲染。

参考:https://reactjs.org/docs/lists-and-keys.html#keys

相关问题