2014-09-24 71 views
5

如何從舊的傳統jQuery湯 代碼更改React組件的狀態?從舊的外部Javascript改變React組件的狀態?

我有這樣一個組件:

var AComponent = React.createClass({ 
    getInitialState: function() { 
    return { ids: [] } 
    }, 
    render: function() { 
    ... 
    }, 
    onButtonClick: function() { 
    ids.splice(…); // remove the last id 
    } 
}); 

當一些特別的東西在舊的jQuery湯代碼發生,我想 推一個ID AComponent.state.ids。我怎樣才能做到這一點?

一個「明顯」的解決方案是反模式;這就是:

var componentInstance = AComtonent({}); 
React.renderComponent(componentInstance, document.getElementById(...)); 

// Somewhere else, in the jQuery soup. Something special happens: 
componentIntance.state.ids.push(1234); 
componentIntance.setState(componentInstance.state); 

這是一個反模式,根據this email from a Facebook developer, 因爲他寫道:componentInstance可能被反應而破壞。

+0

我認爲通過設計一個狀態變異應該是內部的,所以如果你想從外部改變它,你應該使用道具。這意味着你的組件分成兩部分。 IE:將你的狀態轉移到包含你的jQuery湯觸發器的東西,從而解決你的問題。 – 2014-09-25 09:59:30

+0

@plus很高興知道狀態變異應該僅限於內部。我不明白你的意思是什麼*「包含你的jQuery湯觸發器」* - 你的意思是說狀態應該放在組件之外,並且我會將狀態增強器作爲道具傳遞給組件? (正如kulesa的回答一樣。) – KajMagnus 2014-09-26 03:19:26

回答

4

我會使組件無狀態。將ids數組存儲在組件外部,並將其作爲一個道具傳遞給將修改數組的函數。看到JSFiddle的例子:http://jsfiddle.net/ohvco4o2/5/