【问题标题】:Handling form data in PreactJS在 PreactJS 中处理表单数据
【发布时间】:2019-04-03 03:50:12
【问题描述】:

我正在移植一个 react 应用来进行 preact。在提交时处理来自表单的数据会引发TypeError: this.createIssue is not a function at Object.createTestIssue [as click] 错误。

代码如下:

class IssueList extends Component {
  state = { issues: [] };

  createIssue(newIssue) {
    const updatedIssues = this.state.issues.slice();
    newIssue.id = this.state.issues.length + 1;
    updatedIssues.push(newIssue);
    this.setState({ issues: updatedIssues });
  }

  createTestIssue() {
    const issue = {
      status: 'New',
      owner: 'Pieta',
      created: new Date(),
      title: 'Completion date should be optional'
    };
    this.createIssue(issue);
  }

  render(props, state) {
    return (
      <div>
        <h1>Issue Tracker</h1>
        <IssueFilter />
        <hr />
        <IssueTable issues={state.issues} />
        <hr />
        <IssueAdd createIssue={this.createIssue} />
        <hr />
        <button onClick={this.createTestIssue}>Add Test</button>
      </div>
    );
  }
}

export default IssueList;

我试图创建一个构造函数并从构造函数内部设置状态,但是有一个ReferenceError: state is not defined at new IssueList

我查看了 preact 为表单推荐的 linkState 模块,但是我无法正确设置它。我是否传递了一个空对象和一个带有要添加到数组中的数据的对象?类似:

render({}, { state }) {
  ...
}

但这不允许我访问该状态。任何帮助表示赞赏。

【问题讨论】:

  • 你在使用preact-compat吗?可能会使过程更容易,因为它允许您在 preact 中使用 react api。
  • 我正在使用"preact-compat": "^3.18.4"。替换在 React 中工作的整个代码,我现在得到 Uncaught ReferenceError: state is not defined at IssueList.createIssue at IssueList.createTestIssue at HTMLButtonElement.eventProxy
  • 你看到我的回答了吗?我认为你的解构不正确
  • 是的,我按照你的建议解构了render({}, { key, value }) { ... }。当我单击Add Test 按钮时,我仍然得到TypeError: this.createIssue is not a function at Object.createTestIssue [as click]。我错过了什么不允许我访问该功能?

标签: forms preact


【解决方案1】:

正如您所展示的那样,预先将 props 和 state 传递到渲染函数中。

render(props, state) {
  ...
}

这允许您使用destructuring#MOZDocs

render({}, { state }) {
  ...
}

你所拥有的 ^^ 不会是有益的,并且可能会将状态隐藏在另一个对象后面。你应该拥有的是:

render({}, { ...state }) {
  ...
}

或者在我看来最好的解决方案假设state = {key: 'test', value: 1}

render({}, { key, value }) {
  ...
}

如果您不想使用道具中的任何东西,您可以使用如上所示的空对象,或者只使用props,但不要使用它。

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    相关资源
    最近更新 更多