微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

道具在 Reactjs 中是未定义的

如何解决道具在 Reactjs 中是未定义的

嗨,我试图根据 Props 的值为我的应用设置 setState 我依赖 prop 的值作为我的状态,但是当我将函数传递给 setState 时,我收到的道具未定义,不知道为什么,我跟着 this document 参考。您可以阅读状态更新可能是异步的部分 下面是我的代码(来自 File Form.js 的代码片段)

this.props.setTodos(function (_,props) {
      console.log("this is props:" + props);
      return [
        ...props.todos,{ text: props.inputText,completed: false,id: Math.random() *            1000 },];
    });

我传递道具的 App.js 文件代码

import "./App.css";
import Form from "./components/Form";
import TodoList from "./components/TodoList";
import React,{ useState } from "react";
function App() {
  const [inputText,setText] = useState("");
  const [todos,setTodos] = useState([]);
  return (
    <div className="App">
      <header>
        <h1>My Todolist </h1>
      </header>
      <Form
        todos={todos}
        setTodos={setTodos}
        setText={setText}
        inputText={inputText}
      />
      <TodoList />
    </div>
  );
}

export default App;

Form.js 文件的完整代码

import React from "react";

class Form extends React.Component {
  constructor(props) {
    super(props);
  }
  handler = (e) => {
    // console.log(e.target.value);
    this.props.setText(e.target.value);
  };
  submitTodoHandler = (e) => {
    e.preventDefault();

    this.props.setTodos(function (_,id: Math.random() * 1000 },];
    });
  };
  render() {
    return (
      <div>
        <form>
          <input onChange={this.handler} type="text" className="todo-input" />
          <button
            onClick={this.submitTodoHandler}
            className="todo-button"
            type="submit"
          >
            <i className="fas fa-plus-square"></i>
          </button>
          <div className="select">
            <select name="todos" className="filter-todo">
              <option value="all">All</option>
              <option value="completed">Completed</option>
              <option value="uncompleted">Uncompleted</option>
            </select>
          </div>
        </form>
      </div>
    );
  }
}
export default Form;

我不知道为什么我的道具未定义?谢谢

解决方法

您需要做的是更改 submitTodoHandler 组件中的 <Form> 函数:

submitTodoHandler = (e) => {
    e.preventDefault();
    console.log(this.props.inputText) // outputs what you typed in the input
    this.props.setTodos(this.props.inputText);
  };

您在功能组件中定义 setState 并将其作为 prop 传递给类组件。功能组件中的 setState 钩子的行为与您所引用的类组件中的 setState 略有不同。

在功能组件中,setState(或在您的情况下为 setTodos)只需使用 setState(newVariableValue) 即可更改变量的状态,并接受先前状态作为参数。由于 newVariableValue 是通过 prop (inputText) 从 <App> 组件传递到 <Form> 组件,因此您可以使用 this.props.inputText 直接访问它。

Using the State Hook

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。