Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

同步setState这部分有没有demo code? #8

Open
zejunli opened this issue Aug 12, 2021 · 9 comments
Open

同步setState这部分有没有demo code? #8

zejunli opened this issue Aug 12, 2021 · 9 comments

Comments

@zejunli
Copy link

zejunli commented Aug 12, 2021

Promise.then setTimeout/setInterval
new Promise(resolve=>{
resolve()
}).then(()=>{
this.setState({})
})

这个好像依然无法同步获得state,在下一个.then依然拿到的依然是没更新的state

@liubin915249126
Copy link
Owner

react-setStateSync 可以参考下这里

@zejunli
Copy link
Author

zejunli commented Aug 13, 2021

react-setStateSync 可以参考下这里

我在console里面尝试这样,再往后chain一个then不能拿到最新的state,或者说是这么用的吗?

@liubin915249126
Copy link
Owner

这种方式性能不好的,文章里也说了,用 promise 的方式替代callback

@liubin915249126
Copy link
Owner

setStateSync(state){
        return new Promise(resolve=>{
            this.setState(state,resolve)
        })
    }

@zejunli
Copy link
Author

zejunli commented Aug 13, 2021

setStateSync(state){
        return new Promise(resolve=>{
            this.setState(state,resolve)
        })
    }

这个本质还是利用了class component中setstate有callback的性质,在函数component中这个方法就不适用了,我帖子里提到的这一种,在函数component中适用吗?

@liubin915249126
Copy link
Owner

function component 里面react 提供了 useEffect 可以拿到最新的state

@zejunli
Copy link
Author

zejunli commented Aug 13, 2021

function component 里面react 提供了 useEffect 可以拿到最新的state

对,假设不能用useeffect,有没有办法把functional component中的setstate promise化?

@zejunli
Copy link
Author

zejunli commented Aug 13, 2021

new Promise((resolve) => {
	resolve();
}).then(() => {
	setTimeout(() => console.log('in settimeout'), 3000);
  return 'something'
}).then(value => console.log(value));

在这段代码中settimeout模拟setstate的异步操作,到下一个then,还是没有办法在下一个then拿到更新后的数据。。

react-setStateSync 可以参考下这里

@zejunli
Copy link
Author

zejunli commented Aug 13, 2021

react-setStateSync 可以参考下这里

new Promise((resolve, reject) =>{
      resolve()
    }).then(()=>{
      this.setState({done:true})
      console.log(111, this.state.done)
    }).then(() => { // 这里可以保证拿到的是新state吗?貌似不能?});
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants