javascript - 如何在react js中将数据保存在状态数组中

标签 javascript reactjs

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

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

我能够从状态获取 TextField 的文本。我想在单击 FlatButton 时将任务保存在数组中。我有 handleCreateNote 函数,点击 FlatButton 即可附加该函数。

我不知道如何在数组中添加任务。谁能帮助我 react 的方式是什么?

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});
};

查看此答案以了解有关“...”的详细信息 --> 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);

关于javascript - 如何在react js中将数据保存在状态数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44519850/

相关文章:

javascript - 调用多个函数 onClick ReactJS

javascript - 将 React 组件传递给 HTML 属性

javascript - 获取图像 jasmine-Angular 的警告 404

javascript - Highcharts 在初始渲染后更新 pointRange、pointWidth

javascript - 获取所选文本相对于元素的范围

css - 如何在 'Ant Design' 中分隔菜单和菜单选项卡内容宽度?

javascript - React this.props 是一个空对象

javascript - React js中实现Google登录

javascript - 嵌套选项卡中的内容未显示完整的 100% 宽度

javascript - IE 不支持 CustomEvent() 构造函数