[英]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.