javascript - 更改时的 setState

标签 javascript reactjs

出于某种原因,我在我的react的componentDidMount中使用了jquery,但是不能使用this.setState,因为这个已经被jquery方法改变了,我把它设置到别的地方,我可以接受thisComponent.props.something但是为什么setState失败了?

componentDidMount() {
    const thisComponent = this //jquery changed `this`, thus set `this` set to somewhere else

    $('#container').on('scroll', function() {

        console.log(thisComponent.props.something) //work

        thisComponent.setState({ // not working
            myTestingState: true
        })
    })
}

没有错误,我尝试在我的渲染方法中打印出 {this.state.myTestingState.toString()},只是没有设置。

最佳答案

你可以试试这个

componentDidMount() {
    $('#container').on('scroll',() => {    
       this.setState({
          myTestingState: true
       })
    })
}

关于javascript - 更改时的 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44916568/

相关文章:

javascript - 在 JavaScript 中过滤一个值并创建新数组

javascript - 第三次调用后,该函数完美运行 [Google Charts]

javascript - 从外部 Node 进程连接到 Azure Web App/SQL 数据库

javascript - 如何确保 javascript/jquery 总是在返回 true(打开链接)之前完成点击功能?

javascript - 使用隐藏形式将 JavaScript 分数从游戏发送到 PHP - 我没有得到任何值?

javascript - 点击按钮后 Cypress 等待 API

javascript - 在 React 中映射数组 onClick 按钮

javascript - 使用 Filter 函数返回 React 组件 - 代码审查

javascript - 如何在下一个 js 中获取完整的浏览器 url,getServerSideProps

reactjs - 使用 React-Query Hook 有条件地调用 API