javascript - React setState 重新渲染

标签 javascript reactjs

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

据我所知,当您 setState 一个新值时,它会再次渲染 View (或需要重新渲染的部分 View )。

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

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时,它会改变state的key,然后组件<AnotherComponent />应该因为它的参数而改变。

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

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

编辑

我发现paramAnotherComponent收到它不会改变,它总是一样的。

最佳答案

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

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

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

由于我们看不到整个组件,因此很难理解那里实际发生的情况。 我怀疑 newValue 参数始终相同,但我不能确定。
您似乎在 AnotherComponent 的构造函数中缺少 props 。应该是:

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

尝试将 if 语句替换为:

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

还添加此函数来查看新的 props 是否实际到达组件:

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

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

关于javascript - React setState 重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53206695/

相关文章:

javascript - 如何获取特定的动态ID

javascript - 类型错误 : Firebase is not a function

javascript - 为什么我的嵌套组件会自行重建?

reactjs - 使用 Framer Motion 和 NextJS 进行退出动画的布局转换

reactjs - 使用 React 的步进功能

javascript - React-Redux-从列表中删除项目

javascript - polymer 3 相对路径

javascript - 如何使用 webpack 跳过 css 文件中的所有依赖项

javascript - 如何解析 vb.net 中用一堆 document.write 编写的网页?

javascript - 如何将绑定(bind)函数的参数传递给 React 子项?