繁体   English   中英

重组异步道具更新

[英]Recompose async prop update

当从视图组件外部更改prop时,如何使用重新渲染组件?

const Message = ({msg}) => <div>The prop has a value of <b>{msg}</b>.</div>

const App = Recompose.withProps(() => {
  let msg = 'One'

  // this async update doesn't work because nothing triggers a rerender
  setTimeout(() => {msg = 'Two'}, 500)

  return {msg}
})(Message)


ReactDOM.render(<App/>, document.getElementById('app'))

渲染此组件时,它显示的值为1,但是即使更改了prop,它在500ms之后也不会更改为2

在实际的用例中,我订阅了websocket服务器,并且在推送消息时,Message组件得到更新,因此setTimeout简化了这种情况。

免责声明:我还没有积极地进行重组。

但是我知道您的组件应该是有状态的。 在重组文档中发现withState

const enhance = withState('counter', 'setCounter', 0)
const Counter = enhance(({ counter, setCounter }) =>
  <div>
    Count: {counter}
    <button onClick={() => setCounter(n => n + 1)}>Increment</button>
    <button onClick={() => setCounter(n => n - 1)}>Decrement</button>
  </div>
)

所以我认为,您需要使用withState定义状态msg ,然后可以将setMsg传递到组件中。 setTimeout调用此setMsg ,应执行更新。

const withMsg = withState('msg', 'setMessage', '');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM