React-redux:渲染是否总是发生在与调度动作相同的时间内?

前端之家收集整理的这篇文章主要介绍了React-redux:渲染是否总是发生在与调度动作相同的时间内?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的react-redux应用程序中,我有一个受控的文本输入.每次组件更改值时,它都会调度一个操作,最后,值会通过redux循环返回并呈现.

在下面的示例中,这很有效,但在实践中,我遇到了一个问题,即渲染从动作调度异步发生,输入失去光标位置.为了演示这个问题,我添加了另一个显式放入延迟的输入.在单词中间添加一个空格会导致光标在异步输入中跳过.

我有两个关于此的理论,并想知道哪一个是真的:

>这应该可行,但我的生产应用程序中的某个地方有一个导致延迟的错误
>它在简单示例中工作的事实只是运气和react-redux并不能保证渲染会同步发生

哪一个是对的?

工作范例:

http://jsbin.com/doponibisi/edit?html,output

  1. const INITIAL_STATE = {
  2. value: ""
  3. };
  4.  
  5. const reducer = (state = INITIAL_STATE,action) => {
  6. switch (action.type) {
  7. case 'SETVALUE':
  8. return Object.assign({},state,{ value: action.payload.value });
  9. default:
  10. return state;
  11. }
  12. };
  13.  
  14. const View = ({
  15. value,onValueChange
  16. }) => (
  17. <div>
  18. Sync: <input value={value} onChange={(e) => onValueChange(e.target.value)} /><br/>
  19. Async: <input value={value} onChange={(e) => { const v = e.target.value; setTimeout(() => onValueChange(v),0)}} />
  20. </div>
  21. );
  22.  
  23. const mapStateToProps = (state) => {
  24. return {
  25. value: state.value
  26. };
  27. }
  28.  
  29. const mapDispatchToProps = (dispatch) => {
  30. return {
  31. onValueChange: (value) => {
  32. dispatch({
  33. type: 'SETVALUE',payload: {
  34. value
  35. }
  36. })
  37. }
  38. };
  39. };
  40.  
  41.  
  42. const { connect } = ReactRedux;
  43. const Component = connect(
  44. mapStateToProps,mapDispatchToProps
  45. )(View);
  46.  
  47. const { createStore } = Redux;
  48. const store = createStore(reducer);
  49.  
  50. ReactDOM.render(
  51. <Component store={store} />,document.getElementById('root')
  52. );

编辑:澄清问题

Marco和Nathan都正确地指出这是React中的一个已知问题,不会被修复.如果在onChange和设置值之间存在setTimeout或其他延迟,则光标位置将丢失.

但是,setState只调度更新的事实不足以导致此错误发生.在Marco链接Github issue中,有一条评论

Loosely speaking,setState is not deferring rendering,it’s batching
updates and executing them immediately when the current React job has
finished,there will be no rendering frame in-between. So in a sense,
the operation is synchronous with respect to the current rendering
frame. setTimeout schedules it for another rendering frame.

这可以在JsBin示例中看到:“sync”版本也使用setState,但一切正常.

悬而未决的问题仍然是:Redux内部是否存在一些延迟,它允许渲染帧介于其间,或者是否可以以避免这些延迟的方式使用Redux?

我不需要解决手头的问题,我找到一个适用于我的案例,但我有兴趣找到更一般的问题的答案.

编辑:问题解决

我对Clarks的回答很满意,甚至还给了赏金,但事实证明,当我通过删除所有中间件来测试它时,它是错误的.我还发现了与此相关的github问题.

https://github.com/reactjs/react-redux/issues/525

答案是:

>这是react-redux中的一个问题,将使用react-redux 5.1和反应v16进行修复

你在Redux应用程序中使用了什么中间件?也许其中一个就是围绕你的行动派遣承诺.使用没有中间件的Redux不会出现这种行为,所以我认为这可能是您的设置特有的.

猜你在找的React相关文章