2017-02-19 93 views
0

我有這個數據,我的終極版商店:獲取從嵌套數據單個對象在終極版 - Reactjs

data: [ 
    0: { 
     name: "Mark Zuckerburg", 
     description: "Facebook CEO" 
    }, 
    1: { 
     name: "Sheryl Sandberg", 
     description: "Facebook COO" 
    }, 
    2: { 

    } 
] 

這裏的是我在減速代碼:

// This is how I store my data lists 
case GET_HEROES_SUCCESS: { 
      return Object.assign({}, state.data, { 
       data: action.data 
      }); 
     } 
// This is how I fetch currently the single object in the data lists. 
case FETCH_HEROES_REDUX_STORE: { 
      return { ...state, data: state.data[action.id] } 
     } 

我現在的問題是,如果我派遣FETCH_HEROES_REDUX_STORE它覆蓋了我商店中的所有數據列表。如何通過不覆蓋整個數據存儲來僅返回action.id上的單個數據對象庫。

謝謝!

回答

0

在Redux中,操作用於更新和修改狀態。它們通常不用於獲取數據。這是因爲Reducer返回的任何對象都會作爲新的Redux狀態來使用,這就是FETCH_HEROES_REDUX_STORE覆蓋數據列表的原因。

要從Redux中的嵌套數據中獲取單個對象,您希望使用Provider react-redux組件將Redux存儲區傳遞給您的React組件。我鼓勵您查看Redux文檔以更好地理解Redux中的數據流:http://redux.js.org/docs/basics/UsageWithReact.html

在您的最頂層組件中,執行以下操作將您的React組件連接到Redux存儲。這使Redux存儲可用於React應用程序中的所有Container組件。

import React from 'react' 
import { render } from 'react-dom' 
import { Provider } from 'react-redux' 
import { createStore } from 'redux' 
import todoApp from './reducers' 
import App from './components/App' 

let store = createStore(todoApp) 

render(
    <Provider store={store}> 
    <App /> 
    </Provider>, 
    document.getElementById('root') 
) 

然後,要將Redux狀態樹傳遞給React組件,可以將Container組件連接到Redux。注意:您想在React應用程序的某個位置渲染此容器組件。

import { connect } from 'react-redux' 
import ReactComponent from './react_component' // import a React component 

const mapStateToProps = (state) => { 
    return { 
    heroes: state.data // this will return the heroes data directly into your React components so you don't need to fetch it 
    } 
} 

export default connect(mapStateToProps)(ReactComponent) // decorate React component with Redux state 

最後,來自終極版國家訪問單個對象在你的陣營組成:

import React from 'react'; 

const ReactComponent = ({ heroes }) => { 

    console.log(heroes) // will log the redux state tree 

    const markZuckerburg = heroes.data[0] // will log {name: "Mark Zuckerburg", description: "Facebook CEO"} 
    const sherylSandberg = heroes.data[1] // will log {name: "Sheryl Sandberg", description: "Facebook COO"} 

    return (
    <div> {markZuckerburg.name} </div> 
    <div> {sherylSandberg.name} </div> 
) 
} 

export default React Component