首页 > 解决方案 > 从 redux 创建一个引用 store 的 var

问题描述

我目前正在创建一个引用来自 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)
            });
            ...
        }
   }

标签: javascriptreactjsvariablesredux

解决方案


react-redux这是一个可能对您有所帮助的用法示例。不要忘记添加StoreProvider前三个组件(通常命名为App)。

我警告过你一个事实,React并且Redux不适合初学者 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

推荐阅读