尝试使用 setType 并获取类型为“any[]”的参数不可分配给类型为“SetStateAction<undefined>”的参数

时间:2020-12-19 16:48:22

标签: reactjs typescript


const CreateTweet = () => {
  const [textInput, setTextInput] = useState();
  const [tweets, setTweets] = useState();

  const userInputHandler = (e: any) => {
    setTextInput(e.target.value);
  };
  const submitTweetHandler = (e: any) => {
    e.preventDefault();
    setTweets([...tweets, textInput]); //This is where the error is happening : Argument of type 'any[]' is not assignable to parameter of type 'SetStateAction<undefined>'.
  Type 'any[]' provides no match for the signature '(prevState: undefined): undefined'.
    setTextInput(""); //and down here : Argument of type '""' is not assignable to parameter of type 'SetStateAction<undefined>'
  };
  return (
    <form onSubmit={submitTweetHandler}>
      <textarea
        value={textInput} /* connects the value to the form box */
        onChange={userInputHandler}
        cols={50}
        rows={5}
      ></textarea>
      <button>Submit</button>
    </form>
  );
};

export default CreateTweet;

我一直试图让它工作,它在javascript中运行,但由于某种原因,我终生无法弄清楚如何在打字稿上实现这个setTweets函数。感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您需要正确键入 useState。由于 textInput 是一个字符串,您应该最初将其设置为空字符串,并且由于 tweets 将是一个字符串数组,因此也将其键入为字符串数组:

const [textInput, setTextInput] = useState('');
const [tweets, setTweets] = useState<Array<string>>([]);