【问题标题】:ReactJS listView to React Native ListvIewReactJS listView 到 React Native Listview
【发布时间】:2016-09-02 14:42:31
【问题描述】:

我的目标是将 react listView 转换为可用的 react-native ListView。第一个代码是工作 reactJs 代码,第二个是我的 react-native 尝试。主要问题是我需要替换 data.map。这将允许我获取 url。 reference

编辑

我没有收到错误,但 ListView 字段为空。

class App extends Component {

    componentWillMount() {
        this.props.dispatch({type: 'BLAH'});
    }


    render(){
       return (<div>
            {this.props.exception && <span>exception: {this.props.exception}</span>}
            Data: {this.props.data.map(e=><div key={e.id}>{e.url}</div>)}

          </div>);
    }
}

export default connect( state =>({
    data:state.data , exception:state.exception
}))(App);

反应原生列表视图:

class App extends Component {

    constructor(props) {
      super();
      const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      this.state = {
        dataSource: ds.cloneWithRows(props.data)
      };
      console.log(props.data)
    }

    componentWillMount() {
      this.props.dispatch({type: 'BLAH'});
    }

    renderRow(rowData) {
      return (
        <View>
            <Text>{rowData.url}</Text>
        </View>
      );
    }

    render(){
       return (
         <View>
           <ListView dataSource={this.state.dataSource} renderRow={this.renderRow}/>
         </View>
        );
    }
}

export default connect( state =>({
    data:state.data
}))(App);

【问题讨论】:

  • 你有什么问题?
  • 我需要替换 react native 中的 data.map 函数,因为我无法设置 this.props.data
  • 只需将 ['row 1', 'row 2'] 替换为 this.props.data
  • 它是空的。如果你在 app.js 中调试示例,你会看到开头是空的,而在渲染之后它就被填充了
  • 问题可能出在 export default connect(state =>({ data:state.data }))(App);

标签: javascript reactjs react-native


【解决方案1】:

检查the ListView docs。数据源属性采用ListViewDataSource 的实例,而不是您的数据数组。

文档显示了一个最小的示例实现:

getInitialState: function() {
  var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
  return {
    dataSource: ds.cloneWithRows(['row 1', 'row 2']),
  };
},

render: function() {
  return (
    <ListView
      dataSource={this.state.dataSource}
      renderRow={(rowData) => <Text>{rowData}</Text>}
    />
  );
},

【讨论】:

  • 是的,它是文档的摘录,展示了如何为 ListView 提供数据。
  • 我无法从我正在使用的机器访问此页面。
【解决方案2】:

添加componentWillReceiveProps解决问题:

componentWillReceiveProps(newProps) {
  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(newProps.data),
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-25
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 2020-03-16
    • 2015-06-12
    相关资源
    最近更新 更多