簡體   English   中英

從 redux 創建一個引用 store 的 var

[英]Creating a var referencing a store from redux

我目前正在創建一個從 redux 引用商店的 var。 我創建了一個,但在render() 我想避免這種情況並在渲染之外調用它。 這是一個例子。 我被推薦使用componentWillMount() ,但我不確定如何使用它。 這是我實現的代碼片段。 注意:它有效,但僅當我呈現數據時。 我使用雙 JSON.parse 因為它們是帶有 \\ 的字符串

  render() {

        var busData= store.getState().bus.bus;
        var driverData= store.getState().driver.gdriveras;
        var dataReady = false;

        if (busData&& driverData) {
            dataReady = true;
            console.log("========Parsing bus data waterout========");
            var bus_data_json = JSON.parse(JSON.parse(busData));
            console.log(bus_data_json);
            console.log("========Parsing driver data waterout========");
            var driver_data_json = JSON.parse(JSON.parse(driverData));
            console.log(driver_datat_json);

            busDatajson.forEach(elem => {
                elem.time = getFormattedDate(elem.time)
            });

            driverDatajson.forEach(elem => {
                elem.time = getFormattedDate(elem.time)
            });
            ...
        }
   }

這是一個react-redux用法示例,可能會對您有所幫助。 不要忘記將StoreProvider添加到前三個組件(通常命名為App )。

我警告過你, ReactRedux不適合初學者 javascript 開發人員使用。 您應該考慮學習immutability和函數式編程。

// ----

const driverReducer = (state, action) => {

  switch (action.type) {
    // ...
    case 'SET_BUS': // I assume the action type
      return {
        ...state,
        gdriveras: JSON.parse(action.gdriveras) // parse your data here or even better: when you get the response
      }
    // ...
  }

}

// same for busReducer (or where you get the bus HTTP response)
// you can also format your time properties when you get the HTTP response


// In some other file (YourComponent.js)
class YourComponent extends Component {

  render() {
    const {
      bus,
      drivers
    } = this.props

    if (!bus || !drivers) {
      return 'loading...'
    }

    const formatedBus = bus.map(item => ({
      ...item,
      time: getFormattedDate(item.time)
    }))

    const formatedDrivers = drivers.map(item => ({
      ...item,
      time: getFormattedDate(item.time)
    }))

    // return children

  }
}


// this add bus & drivers as props to your component
const mapStateToProps = state => ({
  bus: state.bus.bus,
  drivers: state.driver.gdriveras
}) 

export default connect(mapStateToProps)(YourComponent)
// you have to add StoreProvider from react-redux, otherwise connect will not be aware of your store

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM