【问题标题】:How to parse and print array in React-Native?如何在 React-Native 中解析和打印数组?
【发布时间】:2019-03-23 17:10:10
【问题描述】:

我正在尝试在 react-native 中解析数组并将其打印到控制台。 我的索引和声明可能有问题,我无法访问和打印我的数组。

我在 main.js 中获得了我的数组,但我无法访问 m_uid,m_latitude,m_longitude

我将在 MapView.Marker 中使用这个变量

Array

main.js 中的代码

<MapView.Marker
  coordinate={{
    latitude : "I want to use m_latitude here",
    longitude: "I want to use m_longitude here",
  }}
 /> 

Action.js

 export function AddMark (item){
    return(dispatch)=>{
    dispatch(markSuccess(item));
 }
}

const markSuccess = (markSuccess)=>({
    type: types.MARK_SUCCESS,
    markSuccess,
})

Reducer.js

const initialState = {
   location: {},
    markSuccess:[],
   error : null,
};

const mapsReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.MARK_SUCCESS:
      return {
      ...state,
      markSuccess: action.markSuccess
    };
    default:
      return state;
    }  
  };

export default mapsReducer;

数组输出:

Object {
  "markLocation": Array [
    Object {
    "m_latitude": 52.1769247,
    "m_longitude": 21.0167011,
    "m_uid": "AWxA11i3TQfu3FBguknRsA1y9It2",
    },
    Object {
      "m_latitude": 52.1769243,
      "m_longitude": 21.0167014,
      "m_uid": "I37DYEJt9vbdDw78iPW0hC4DcuZ2",
    },
  ],
}

Main.js

render() {
  const { markLocation } = this.props;
  console.log("arr",{markLocation});
}

const mapStateToProps = ({ mapsReducer:{location,error,markSuccess}}) => ({
  markLocation:markSuccess
});

const mapDispatchToProps = { };

export default connect(mapStateToProps, mapDispatchToProps)(Map);

我将 react-native expo 与 redux 一起使用。

【问题讨论】:

  • 我在这里看不到足够的代码来判断您正在正确声明变量或正确传递道具。我知道你不应该在你的 console.log() 中使用花括号,它们是不必要的。
  • 你好,我只想如何访问这个数组如何打印它,例如在 foreach { console.log(marklocation[0].uid) } == 将给出 uid 输出但我不能访问

标签: javascript arrays react-native


【解决方案1】:

我不确定你做错了什么,因为我看不到 props 有什么,也看不到你在哪里创建了一个数组。但是要在 react-native 中创建一个数组,请执行以下操作:

constructor(props) {
    super(props)
    this.state = {
        array:[],
    }
}

为了管理数组,我建议将 state 的值分配给一个临时的“正常”变量,有很多方法可以做到这一点,这对我来说是最简单和容易的。

let array=this.state.array;
array.push('one more value');
this.setState({array})

【讨论】:

  • 感谢您的评论,我再次更新了我的主题。你能再检查一下吗?
  • 很抱歉,回答太晚了,但它对我有用,谢谢。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 2016-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多