微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

在我的react-redux应用程序中,我有一个受控的文本输入.每次组件更改值时,它都会调度一个操作,最后,值会通过redux循环返回并呈现.

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

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

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

一个是对的?

工作范例:

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

const INITIAL_STATE = {
  value: ""
};

const reducer = (state = INITIAL_STATE,action) => {
  switch (action.type) {
    case 'SETVALUE':
      return Object.assign({},state,{ value: action.payload.value });
    default:
      return state;
  }
};

const View = ({
  value,onValueChange
}) => (
  <div>
    Sync: <input value={value} onChange={(e) => onValueChange(e.target.value)} /><br/>
    Async: <input value={value} onChange={(e) => { const v = e.target.value; setTimeout(() => onValueChange(v),0)}} />
  </div>
);

const mapStatetoProps = (state) => {
  return {
    value: state.value
  };
}

const mapdispatchToProps = (dispatch) => {
  return {
    onValueChange: (value) => {
      dispatch({
        type: 'SETVALUE',payload: {
          value
        } 
      })            
    }
  };
};


const { connect } = ReactRedux;
const Component = connect(
  mapStatetoProps,mapdispatchToProps
)(View);

const { createStore } = Redux;
const store = createStore(reducer);

ReactDOM.render(
  <Component store={store} />,document.getElementById('root')
);

编辑:澄清问题

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不会出现这种行为,所以我认为这可能是您的设置特有的.

原文地址:https://www.jb51.cc/react/301047.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐