代码之家  ›  专栏  ›  技术社区  ›  Zander

反应设置状态重新渲染

  •  0
  • Zander  · 技术社区  · 6 年前

    首先,我对React真的很陌生,所以请原谅我对这个问题缺乏了解。

    我有这样的事情,我想知道这是不是一个好的做法,我如何才能解决这类问题,以改善等。

    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>
                }
            )
        }
    }
    

    代码的意图是,当我单击span时,它将更改状态的键,然后更改组件 <AnotherComponent />

    我保证当我创建setState时,在回调中抛出一个带有新值的控制台日志,并且设置正确,但是 AnotherComponent 不会更新,因为根据给定的参数,它会显示一件事或另一件事。

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

    我发现 param 那个 接受它是不变的,总是一样的。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Yoav    6 年前

    我建议你先用一个简单的 console.log 在你的 changeValue

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

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

    因为我们看不到整个组件,所以很难理解那里到底发生了什么。 我怀疑 newValue 参数总是一样的,但我不能确定。
    props 在里面 AnotherComponent

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

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

    还要添加此函数以查看新道具是否真正到达组件:

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

    param someOptions 既然你在(正当地)使用 === 比较。

        2
  •  0
  •   Mosè Raguzzini    6 年前