const { useState } = React; const 示例 = () => { const [完成,setDone] = useState(false); const [数据,setData] = useState({}); const demoData = Array.from(Array(20).keys()); const demoResolver = (x) =>;新的 Promise(res => setTimeout(() => res(x), Math.random() * 1250)) const loadData = () =>; { const Promise = demoData.map(c => demoResolver(c)); Promise.forEach(promise => { 承诺 .then(r => { setTimeout(() => { setData(p => ({ ...p, [r]: r })); }, 500); }) }); Promise.all(承诺) .then(r => { console.log('Promise.all.then: ', r.length) 设置完成(真); }) } console.log('渲染', Object.keys(data).length); const ProgressBarIsShownDebugColor =(完成) ? '是危险' : '是信息'; 返回 ( <节类名='节'>;{'示例'}
; <进展 最大值={demoData.length} value={Object.keys(data).length} className={'progress my-3' + ProgressBarIsShownDebugColor} >> </节> ) } ReactDOM.render(<示例/>, document.getElementById("react"));
.as-console-wrapper { max-height: 50px !important; }</pre> <pre class="brush:html;toolbar:false;"><script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min .js"></脚本> <脚本 src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <链接 rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css"> <div id="react"></div></pre> <p><br />></p>
P粉4267805152023-08-21 00:02:16
上面代码中显示的问题是,在获取数据后,在设置状态之前有额外的500ms异步延迟。在实际代码中,听起来有额外的处理(可能是同步的)导致setData
在.all
之后被调用。
最好的做法是将done
作为一个计算属性而不是一个单独的状态,因为在那个点上,您不需要依赖于状态设置竞争,并且Object.keys(data).length
足够便宜,不会降低性能(而且您在其他区域使用它,如果它成为一个问题,您可以将其缓存到一个变量中)。
const [data, setData] = useState({}); const done = Object.keys(data).length === 20; // 在实际代码中为200
const { useState } = React; const Example = () => { const [data, setData] = useState({}); const done = Object.keys(data).length === 20; // 在实际代码中为200 const demoData = Array.from(Array(20).keys()); const demoResolver = (x) => new Promise(res => setTimeout(() => res(x), Math.random() * 1250)) const loadData = () => { const promises = demoData.map(c => demoResolver(c)); promises.forEach(promise => { promise .then(r => { setTimeout(() => { setData(p => ({ ...p, [r]: r })); }, 500); }) }); } console.log('Render', Object.keys(data).length); const progressBarIsShownDebugColor = (done) ? 'is-danger' : 'is-info'; return ( <section className='section'> <h1 className='title is-3'>{'Example'}</h1> <progress max={demoData.length} value={Object.keys(data).length} className={'progress my-3 ' + progressBarIsShownDebugColor} /> <button onClick={loadData}>Start</button> </section> ) } ReactDOM.render(<Example />, document.getElementById("react"));
.as-console-wrapper { max-height: 50px !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css"> <div id="react"></div>