1
我無法弄清楚爲什麼我的組件呈現既前的道具和新的道具,而不是隻有差異。以前的狀態是渲染(重複)與新狀態
例如它呈現:
[[1, 2, 3, 4, 5]]
[[6, 7, 8, 9, 10]]
[[1, 2, 3, 4, 5]]
[[6, 7, 8, 9, 10]]
[[16, 57, 8, 19, 5]]
而不只是:
[[1, 2, 3, 4, 5]]
[[6, 7, 8, 9, 10]]
[[16, 57, 8, 19, 5]]
我的主要成分:
class AsyncApp extends Component {
constructor(props) {
super(props)
}
lookForUpdate() {
// this function hits a endpoint every 10 sec.
setInterval(() => {
this.props.dispatch(fetchDataForReals())
}, 10000)
}
componentDidMount() {
this.props.dispatch(fetchDataForReals())
this.lookForUpdate()
}
render() {
const { graphData } = this.props;
return (
<div>
<div>hello</div>
<DataGraph graphData={graphData} />
</div>
)
}
}
function mapStateToProps(state) {
let graphData = state.payment.graphDatas
return {
graphData
}
}
export default connect(mapStateToProps)(AsyncApp)
我的其他組件:
import React, { Component } from 'react'
export default class DataGraph extends Component {
constructor(props) {
super(props)
}
shouldComponentUpdate(nextProps) {
return nextProps.graphData !== this.props.graphData
}
render() {
return (
<div>{this.props.graphData.map(function(datas){
return datas.map(function(data, index){
return <li key={index}>{data.series}</li>
})
})}</div>
)
}
}
export default DataGraph;
我action.js
function requestDataArray() {
return {
type: REQUEST_DATA
}
}
function recieveDataArray(data) {
return {
type: RECIEVE_DATA,
data: data.map(child => child),
receivedAt: Date.now()
}
}
function fetchData() {
return dispatch => {
dispatch(requestDataArray())
return fetch('//localhost:3000/api/v1/data', {
mode: 'no-cors'
}).then(function(data){
return data.json()
}).then(function(data){
dispatch(recieveDataArray(data))
})
}
}
export function fetchDataForReals() {
return (dispatch) => {
return dispatch(fetchData())
}
}
我減速器:
const initialState = {
graphDatas: [],
friendsList : {},
comments: []
}
function addData(state = initialState.graphDatas, action) {
switch(action.type) {
case 'RECIEVE_DATA':
var clone = _.cloneDeep(state);
var resultPopOff = clone.pop()
let stateResult = _.isEqual(resultPopOff, action.data)
if (stateResult) {
return state
} else {
return [
...state, action.data
]
}
default:
return state;
}
}
const payment = (state = initialState, action) => {
switch(action.type) {
default:
return {
graphDatas: addData(state.graphDatas, action)
}
}
}
const rootReducer = combineReducers({
payment, routing: routerReducer
})
export default rootReducer
哈哈,是的,謝謝! –
爲什麼不......國家的工作,克隆呢? –
當你做一個'state'的克隆,然後改變這個克隆,狀態不會改變,只有克隆會改變。所以'clone.pop()'的邏輯是獨立的,但不會從最初的'state'對象中刪除任何東西(直到整個函數返回,* * redux將會更新整個狀態。 –