const Feed = React.createClass({
getInitialState: function() {
return {
data: {}
}
},
componentDidMount: function() {
axios.all([
getAllTeams(), getAllDrivers()
]).then((results) => {
let teams = results[0].data;
let drivers = results[1].data;
let newDrivers = normaliseDrivers(drivers);
var data = normaliseData(teams, newDrivers);
this.setState({
data: data
})
})
},
sortAndRenderPanels() {
let teamsArr = Object.values(this.state.data);
teamsArr.sort(function(a,b) {
return (a.positions[0][2016] > b.positions[0][2016])
? 1 : ((b.positions[0][2016] > a.positions[0][2016])
? -1 : 0);
});
return teamsArr.map ((data, i) => {
return (
<MyPanel
key={i}
data={data}
/>
)
})
},
sortAlphabeticallyAndRender() {
let teamsArr = Object.values(this.state.data);
var sorted = teamsArr.sort(function(a, b){
var textA = a.name.toUpperCase();
var textB = b.name.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
return sorted.map((data, i) => {
return (
<MyPanel
key={i}
data={data}
/>
)
})
},
handleAlphabetClick (e) {
e.preventDefault();
this.sortAlphabeticallyAndRender(this.state);
this.forceUpdate(function() {
return this.state.data;
});
},
render: function() {
const cards = this.sortAndRenderPanels();
return (
<div id="feed">
<Button id='sort-button' onClick={this.handleAlphabetClick} type="button" className="btn btn-warning" aria-label="Left Align">
<span > Sort Alphabetically</span>
</Button>
{cards}
</div>
)
}
});
On按鈕單擊我想重新渲染面板,以按字母順序顯示。我知道我的函數來正確命令它們的工作,並以正確的順序將數據記錄到控制檯,但似乎無法強制更新來重新呈現狀態。對狀態變化的React重新渲染
作爲一個反應的最佳實踐,永遠不要做forceUpdate(直到你確定你爲什麼要進行強制更新)。用戶setState()用於fire渲染方法 –