如何在反应js中将数据保存在状态数组中

How to save data in an array inside state in react js

我在 Dialog 里面有 TextFieldFlatButton。我想将完整的任务列表保存在我在状态中定义的数组中。

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;

首先创建现有状态数组的副本,然后使用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});
};

查看此答案以获取有关“...”的详细信息 -->

MDN:Spread Operator

更新:

您也可以使用 slice() 而不是扩展运算符,这也会 return 一个新数组,关键是我们需要创建状态数组的副本(在进行任何更改之前)使用任何方法。

检查这个片段:

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

let b = [...a];

console.log('b', b);

您可以使用 concat 创建一个新的 array:

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