Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript react输入值需要由useState钩子设置,以便运行onChange事件,但它';我运行了一个变种后,它是空的_Javascript_Reactjs_Graphql_Aws Amplify - Fatal编程技术网

Javascript react输入值需要由useState钩子设置,以便运行onChange事件,但它';我运行了一个变种后,它是空的

Javascript react输入值需要由useState钩子设置,以便运行onChange事件,但它';我运行了一个变种后,它是空的,javascript,reactjs,graphql,aws-amplify,Javascript,Reactjs,Graphql,Aws Amplify,我正在使用aws amplify react和graphql 我主要关注的是recipe.components.items.map中的输入,如果我使用val.component作为值,它将在刷新时显示正确的值,但是我无法通过onChange更新输入,输入什么都不做,这很有意义,但是如何从updatecurrentigredent函数中获取新的更新值,以便在刷新时显示。我需要订阅吗,但我不知道这对我有什么帮助 理想情况下,当我从要运行的输入中拉出制表符或单击时,以及当我刷新页面时,输入将反映更改

我正在使用aws amplify react和graphql

我主要关注的是
recipe.components.items.map中的输入,如果我使用val.component作为值,它将在刷新时显示正确的值,但是我无法通过
onChange
更新输入,输入什么都不做,这很有意义,但是如何从
updatecurrentigredent
函数中获取新的更新值,以便在刷新时显示。我需要订阅吗,但我不知道这对我有什么帮助

理想情况下,当我从要运行的输入中拉出制表符或单击时,以及当我刷新页面时,输入将反映更改

我想这样做的原因是,最终我希望能够添加多个成分,但在添加新的成分输入行之前,我需要能够更新成分

这是我的食谱编辑页面,需要能够通过一个重复按钮添加配料,新行新配料,但我首先关注的是能够更新一种配料

如果你有更好的想法来设计这个,我洗耳恭听

提前谢谢

这是到目前为止我的代码

import { useEffect, useState } from "react";
import { API } from "aws-amplify";
import { updateIngredient, updateRecipe } from "./graphql/mutations";
import { getRecipe } from "./graphql/queries";
import { useParams } from "react-router-dom";

function EditRecipe() {
  const [recipe, setRecipe] = useState(null);
  const [ingredients, setIngredients] = useState(null);
  let { id } = useParams();

  useEffect(() => {
    fetchRecipe();
    async function fetchRecipe() {
      if (!id) return;
      const recipeData = await API.graphql({
        query: getRecipe,
        variables: { id },
        authMode: "API_KEY",
      });
      setRecipe(recipeData.data.getRecipe);
      setIngredients(recipeData.data.getRecipe.ingredients);
    }
  }, [id]);

  if (!recipe) return null;

  function onChange(e) {
    setRecipe({ ...recipe, [e.target.name]: e.target.value });
  }

  const { name } = recipe;

  async function updateCurrentPost() {
    if (!name) return;
    await API.graphql({
      query: updateRecipe,
      variables: { input: { name, id } },
      authMode: "AMAZON_COGNITO_USER_POOLS",
    });
    console.log("post successfully updated!");
  }

  if (!ingredients) return null;

  function onChangeIngredient(e) {
    setIngredients({ ...ingredients, [e.target.name]: e.target.value });
    console.log(e);
  }

  async function updateCurrentIngredient(id, ingredient) {
    console.log(id + " " + ingredients.ingredient);
    if (!ingredients) return;
    await API.graphql({
      query: updateIngredient,
      variables: { input: { ingredient: ingredients.ingredient, id } },
      authMode: "AMAZON_COGNITO_USER_POOLS",
    });
    console.log("ingredient succesfully updated");
  }

  return (
    <>
      <div>
        {recipe && (
          <input
            name="name"
            value={recipe.name}
            placeholder="name"
            value={recipe.name}
            onChange={onChange}
          />
        )}
      </div>
      <div>
        <>
          {recipe.ingredients.items.map((val, i) => {
            return (
              <ul key={i}>
                <li>
                  <p>Choose ingredient</p>
                  <input
                    name="ingredient"
                    placeholder="name"
                    value={ingredients.ingredient}
                    onChange={onChangeIngredient}
                    onBlur={() => {
                      updateCurrentIngredient(val.id);
                    }}
                  />
                </li>
              </ul>
            );
          })}
        </>
      </div>
      <div>
        <button onClick={updateCurrentPost}>Update Post</button>
      </div>
    </>
  );
}

export default EditRecipe;
从“react”导入{useffect,useState};
从“aws放大”导入{API};
从“/graphql/translations”导入{UpdateIngCredit,updateRecipe}”;
从“/graphql/querys”导入{getRecipe};
从“react router dom”导入{useParams};
函数EditRecipe(){
const[recipe,setRecipe]=useState(null);
const[components,setcomponents]=useState(null);
设{id}=useParams();
useffect(()=>{
fetchRecipe();
异步函数fetchRecipe(){
如果(!id)返回;
const recipeData=await API.graphql({
查询:getRecipe,
变量:{id},
authMode:“API_密钥”,
});
setRecipe(recipeData.data.getRecipe);
SetComponents(recipeData.data.getRecipe.Components);
}
},[id]);
如果(!recipe)返回null;
函数onChange(e){
setRecipe({…recipe[e.target.name]:e.target.value});
}
const{name}=recipe;
异步函数updateCurrentPost(){
如果(!name)返回;
等待API.graphql({
查询:updateRecipe,
变量:{input:{name,id}},
authMode:“AMAZON\u COGNITO\u用户\u池”,
});
log(“post已成功更新!”);
}
如果(!配料)返回空值;
功能(e){
setComponents({…Components,[e.target.name]:e.target.value});
控制台日志(e);
}
异步函数updatecurrentinegredient(id,成分){
console.log(id+“”+配料.配料);
如果(!成分)返回;
等待API.graphql({
查询:updateCredit,
变量:{input:{component:components.component,id}},
authMode:“AMAZON\u COGNITO\u用户\u池”,
});
控制台日志(“成分成功更新”);
}
返回(
{配方&&(
)}
{recipe.components.items.map((val,i)=>{
返回(
  • 选料

    { 更新当前日期(val.id); }} />
); })} 更新帖子 ); } 导出默认编辑配方;
更新:我仍然很执着于此,我已经尝试将inptu移动到其中;s自己的组件,让我困惑的是如何从映射中获取值并更新它,在下面的代码中,我修改了输入值,但它根本不起作用。这是有道理的,但我不知道现在该怎么办

// pages/edit-post/[id].js
import { useEffect, useState } from "react";
import { API } from "aws-amplify";
import { updateIngredient, updateRecipe } from "./graphql/mutations";
import { listIngredients } from "./graphql/queries";
import { getRecipe } from "./graphql/queries";
import { useParams } from "react-router-dom";
import Ingredient from "./Ingredient";

function IngredientInput(props) {
  const [ingredients, setIngredients] = useState(props.item);

  const onChangeIngredient = (e) => {
    setIngredients({ ...ingredients, [e.target.name]: e.target.value });
  };

  async function updateCurrentIngredient(id, ingredient) {
    console.log(id + " " + ingredients.ingredient);
    if (!ingredients) return;
    await API.graphql({
      query: updateIngredient,
      variables: { input: { ingredient: ingredients.ingredient, id } },
      authMode: "AMAZON_COGNITO_USER_POOLS",
    });
    console.log("ingredient succesfully updated");
  }

  return (
    <div>
      <input value={props.item.ingredient} onChange={onChangeIngredient} />
      <button
        onClick={() => {
          updateCurrentIngredient(props.item.id);
        }}
      >
        Save ingredient
      </button>
    </div>
  );
}

function EditRecipe() {
  const [recipe, setRecipe] = useState(null);
  const [ingredients, setIngredients] = useState(null);
  let { id } = useParams();

  //console.log(id);

  useEffect(() => {
    fetchRecipe();
    async function fetchRecipe() {
      if (!id) return;
      const recipeData = await API.graphql({
        query: getRecipe,
        variables: { id },
        authMode: "API_KEY",
      });
      setRecipe(recipeData.data.getRecipe);
      setIngredients(recipeData.data.getRecipe.ingredients);
    }
  }, [id]);

  if (!recipe) return null;

  function onChange(e) {
    setRecipe({ ...recipe, [e.target.name]: e.target.value });
  }

  const { name } = recipe;

  async function updateCurrentPost() {
    if (!name) return;
    await API.graphql({
      query: updateRecipe,
      variables: { input: { name, id } },
      authMode: "AMAZON_COGNITO_USER_POOLS",
    });
    console.log("post successfully updated!");
  }

  return (
    <>
      <div>
        {recipe && (
          <input
            name="name"
            value={recipe.name}
            placeholder="name"
            value={recipe.name}
            onChange={onChange}
          />
        )}
      </div>
      <div>
        {/* {recipe.ingredients.items && ( */}
        <>
          {ingredients.items.map((val, i) => {
            return (
              <IngredientInput key={i} item={val} />
            );
          })}
        </>
        {/* )} */}
      </div>
      <div>
        <button onClick={updateCurrentPost}>Update Post</button>
      </div>
    </>
  );
}

export default EditRecipe;
//pages/edit post/[id].js
从“react”导入{useffect,useState};
从“aws放大”导入{API};
从“/graphql/translations”导入{UpdateIngCredit,updateRecipe}”;
从“/graphql/querys”导入{listComponents}”;
从“/graphql/querys”导入{getRecipe};
从“react router dom”导入{useParams};
从“/成分”进口成分;
功能IngRadientInput(道具){
常量[成分,设置成分]=使用状态(道具项目);
const onChangeComponent=(e)=>{
setComponents({…Components,[e.target.name]:e.target.value});
};
异步函数updatecurrentinegredient(id,成分){
console.log(id+“”+配料.配料);
如果(!成分)返回;
等待API.graphql({
查询:updateCredit,
变量:{input:{component:components.component,id}},
authMode:“AMAZON\u COGNITO\u用户\u池”,
});
控制台日志(“成分成功更新”);
}
返回(
{
UpdateCurrentDient(props.item.id);
}}
>
保存成分
);
}
函数EditRecipe(){
const[recipe,setRecipe]=useState(null);
const[components,setcomponents]=useState(null);
设{id}=useParams();
//console.log(id);
useffect(()=>{
fetchRecipe();
异步函数fetchRecipe(){
如果(!id)返回;
const recipeData=await API.graphql({
查询:getRecipe,
变量:{id},
authMode:“API_密钥”,
});
setRecipe(recipeData.data.getRecipe);
SetComponents(recipeData.data.getRecipe.Components);
}
},[id]);
如果(!recipe)返回null;
函数onChange(e){
setRecipe({…recipe[e.target.name]:e.target.value});
}
const{name}=recipe;
异步函数updateCurrentPost(){
如果(!name)返回;
等待API.graphql({
查询:updateRecipe,
变量:{input:{name,id}},
authMode:“AMAZON\u COGNITO\u用户\u池”,
});
log(“post已成功更新!”);
}
返回(
// pages/edit-post/[id].js
import React, { useEffect, useState } from "react";
import { API } from "aws-amplify";
import { updateIngredient, updateRecipe } from "./graphql/mutations";
import { listIngredients } from "./graphql/queries";
import { getRecipe } from "./graphql/queries";
import { useParams } from "react-router-dom";
import Ingredient from "./Ingredient";

function IngredientInput(props) {
  let { id } = useParams();

  const [ingredients, setIngredients] = useState(props.item);

  const onChangeIngredient = (e) => {
    setIngredients([{ ...ingredients, [e.target.name]: e.target.value }]);
  };

  async function fetchRecipe() {
    if (!id) return;
    const recipeData = await API.graphql({
      query: getRecipe,
      variables: { id },
      authMode: "API_KEY",
    });
    setIngredients(recipeData.data.getRecipe.ingredients.items);
    console.log(recipeData.data.getRecipe.ingredients.items);
  }

  useEffect(() => {
    fetchRecipe();
  }, [id]);

  async function updateCurrentIngredient(id, ingredient) {
    console.log(id + " " + ingredient);
    if (!ingredients) return;
    await API.graphql({
      query: updateIngredient,
      variables: { input: { ingredient: ingredient, id } },
      authMode: "AMAZON_COGNITO_USER_POOLS",
    });
    console.log("ingredient succesfully updated");
  }

  console.log(ingredients);

  return (
    <div>
      {ingredients.map((test, i) => {
        return (
          <React.Fragment key={i}>
            <input
              name="ingredient"
              value={test.ingredient}
              onChange={onChangeIngredient}
            />
            <button
              onClick={() => {
                updateCurrentIngredient(props.id, test.ingredient);
              }}
            >
              Save ingredient
            </button>
          </React.Fragment>
        );
      })}
    </div>
  );
}

function EditRecipe() {
  const [recipe, setRecipe] = useState(null);
  const [ingredients, setIngredients] = useState(null);
  let { id } = useParams();

  //console.log(id);

  async function fetchRecipe() {
    if (!id) return;
    const recipeData = await API.graphql({
      query: getRecipe,
      variables: { id },
      authMode: "API_KEY",
    });
    setRecipe(recipeData.data.getRecipe);
    setIngredients(recipeData.data.getRecipe.ingredients);
  }

  useEffect(() => {
    fetchRecipe();
  }, [id]);

  if (!recipe) return null;

  function onChange(e) {
    setRecipe({ ...recipe, [e.target.name]: e.target.value });
  }

  const { name } = recipe;

  async function updateCurrentPost() {
    if (!name) return;
    await API.graphql({
      query: updateRecipe,
      variables: { input: { name, id } },
      authMode: "AMAZON_COGNITO_USER_POOLS",
    });
    fetchRecipe();
    console.log("post successfully updated!");
  }

  return (
    <>
      <div>
        {recipe && (
          <input
            name="name"
            value={recipe.name}
            placeholder="name"
            value={recipe.name}
            onChange={onChange}
          />
        )}
      </div>
      <div>
        {/* {recipe.ingredients.items && ( */}
        <>
          {ingredients &&
            ingredients.items.map((val, i) => {
              return (
                <IngredientInput id={val.id} key={i} item={ingredients.items} />
              );
            })}
        </>
        {/* )} */}
      </div>
      <div>
        <button onClick={updateCurrentPost}>Update Post</button>
      </div>
    </>
  );
}

export default EditRecipe;