【发布时间】:2021-09-19 01:21:06
【问题描述】:
嗨,我试图根据 Props 的值为我的应用程序 setState 我依赖于我的 state 的 props 值,但是当我将函数传递给 setState 时,我收到的 props 是未定义的,不知道为什么,我关注this document 以供参考。您可以阅读状态更新可能是异步的部分 下面是我的代码(来自 File Form.js 的代码 sn-p)
this.props.setTodos(function (_, props) {
console.log("this is props:" + props);
return [
...props.todos,
{ text: props.inputText, completed: false, id: Math.random() * 1000 },
];
});
我传递 props 的 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 (_, props) {
console.log("this is props:" + props);
return [
...props.todos,
{ text: props.inputText, completed: false, 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;
我不知道为什么我的道具是未定义的?谢谢
【问题讨论】:
-
您需要从
this.props.setTodos函数中删除props参数,因为它只接受prevState 参数 -
如果我删除参数如何访问道具,请详细说明@alexnik42,文档说它也接受道具
-
你已经在你的构造函数中传递了 props,所以你可以直接在 props.setTodos 函数中访问它们。
-
是的,但是文档说这不是一个好习惯,因为有时它可能会导致错误,因为进程是异步的 @alexnik42
-
文档说它也接受道具,文档指的是
setState类方法。setTodos是钩子。两者都是不同的东西。
标签: javascript reactjs ecmascript-6 react-state