本机反应原因this.setState不会重新呈现子组件

时间:2015-06-06 06:57:25

标签: react-native

我正在尝试用native native编写一个待办事项应用程序。我已经确认持有所有待办事项的状态正在接收用户添加的待办事项。 this.setState不会触发重新渲染。任何人都有任何想法为什么?从我所看到的,this.setState应该触发重新渲染。

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  TouchableHighlight,
  ListView
} = React;

var AwesomeProject = React.createClass({
  getInitialState: function(){
    return{
      toDos: ["hello world", "jake"]
    }
  },
  addToDo: function(todo){
    console.log(todo)  //this is printing the todo item added
    this.setState({
      toDos: this.state.toDos.concat([todo])
    });
    console.log(this.state.toDos) //this is printing state with item added
  },
  render: function() {
    return (
      <View>
        <Input addNew={this.addToDo} />
        <ToDos toDos={this.state.toDos} />
      </View>
    );
  }
});


var ToDos = React.createClass({
  getInitialState: function(){
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
      dataSource: ds.cloneWithRows(this.props.toDos)
    };
  },
  render: function(){
      return (
        <ListView dataSource={this.state.dataSource} renderRow={(rowData) => <Text>{rowData}</Text>}/>
      )
    }
});

var Input = React.createClass({
  getInitialState: function(){
      return {
        inputTxt: ''
      }
    },
    updateInput: function(e){
      this.setState({
        inputTxt: e.target.value
      });
    },
    handleAddNew: function(){
      this.props.addNew(this.state.inputTxt);
      this.setState({
        inputTxt: ''
      });
    },
    render: function(){
      return (
          <View>
            <Text> Input todo:
            </Text>
            <TextInput style={{height: 40, borderColor: 'gray', borderWidth: 1}} type="text" value={this.state.inputTxt} onChange={this.updateInput} onChangeText={(text) => this.setState({inputTxt: text})}/>
            <TouchableHighlight onPress={this.handleAddNew}><Text>Add Todo </Text></TouchableHighlight>
          </View>
      );
    }

});


var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

尝试

componentWillReceiveProps(nextProps) { 
   this.setState({ dataSource: dataSource.cloneWithRows(nextProps.toDos) 
}

答案 1 :(得分:1)

您的ToDos组件看起来需要componentWillReceiveProps方法:https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops

相关问题