在下面的示例中,这很有效,但在实践中,我遇到了一个问题,即渲染从动作调度异步发生,输入失去光标位置.为了演示这个问题,我添加了另一个显式放入延迟的输入.在单词中间添加一个空格会导致光标在异步输入中跳过.
我有两个关于此的理论,并想知道哪一个是真的:
>这应该可行,但我的生产应用程序中的某个地方有一个导致延迟的错误
>它在简单示例中工作的事实只是运气和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进行修复