如何在react js中的状态内保存数据

时间:2017-06-13 11:09:19

标签: javascript reactjs

TextField内有FlatButtonDialog。我想将完整的任务列表保存在我在状态中定义的数组中。

this.state = {
  open: false,
  todos: [{ id: -1, text: "", completed: false }],
  notetext: ""
};

我可以从州获取TextField的文字。我希望在点击FlatButton时将任务保存在数组中。我有handleCreateNote功能,可以点击FlatButton

我不知道在数组中添加任务的方法是什么。任何人都可以帮助我做出反应的方式吗?

const AppBarTest = () =>
  <AppBar
    title={strings.app_name}
    iconClassNameRight="muidocs-icon-navigation-expand-more"
    style={{ backgroundColor: colors.blue_color }}
  />;

class App extends Component {
  constructor(props) {
    injectTapEventPlugin();
    super(props);
    this.state = {
      open: false,
      todos: [{ id: -1, text: "", completed: false }],
      notetext: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleOpen = () => {
    this.setState({ open: true });
  };

  handleClose = () => {
    this.setState({ open: false });
  };

  handleCreateNote = () => {
    console.log(this.state.notetext);
  };

  handleChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }

  render() {
    return (
      <MuiThemeProvider>
        <div>
          <AppBarTest />
          <FloatingActionButton
            style={styles.fab}
            backgroundColor={colors.blue_color}
            onTouchTap={this.handleOpen}
          >
            <ContentAdd />
          </FloatingActionButton>
          <Dialog
            open={this.state.open}
            onRequestClose={this.handleClose}
            title={strings.dialog_create_note_title}
          >
            <TextField
              name="notetext"
              hintText="Note"
              style={{ width: "48%", float: "left", height: 48 }}
              defaultValue={this.state.noteVal}
              onChange={this.handleChange}
            />

            <div
              style={{
                width: "4%",
                height: "48",
                backgroundColor: "red",
                float: "left",
                visibility: "hidden"
              }}
            />

            <FlatButton
              label={strings.create_note}
              style={{ width: "48%", height: 48, float: "left" }}
              onTouchTap={this.handleCreateNote}
            />
          </Dialog>

        </div>
      </MuiThemeProvider>
    );
  }
}

export default App;

2 个答案:

答案 0 :(得分:4)

首先创建现有状态数组的副本,然后使用array.push添加新数据,然后使用setState更新状态数组值。

像这样:

handleCreateNote = () => {
    let todos = [...this.state.todos];   //creating the copy

    //adding new data
    todos.push({
        id: /*unique id*/,
        text: this.state.notetext,
        completed: false
    });

    //updating the state value
    this.setState({todos});
};

请查看此答案,详细了解“ ... ” - &gt; What do these three dots in React do?

MDN:Spread Operator

<强>更新

您也可以使用slice()代替传播运算符,这也将返回一个新数组,关键点是我们需要创建状态数组的副本(在进行任何更改之前) )使用任何方法。

检查此代码段:

let a = [{key: 1}, {key: 2}];

let b = [...a];

console.log('b', b);

答案 1 :(得分:1)

您可以使用concat创建新的array

this.setState({
    todos: [].Concat(this.state.todos, {id, text,  complete})
})