简体   繁体   English

如何在反应中更新 state?

[英]How to update state in react?

I am new to react....I am stuck in this problem for many days..but not able to find a solution.. I want to achieve this:我是新来的反应....我被这个问题困了很多天..但找不到解决方案..我想实现这个:

When the Patent component mounts I want to fetch data from my server which am I doing by useeffect and display it on the screen (the data is list of emails)....Then there is add email button..when user click on it a popup Modal () appears which I handled through EmailModal usestate...In the popup user can add new email and onclick submit button the email get send to the server...and the popup closes and screen should get updated with this new email along with previous email当 Patent 组件安装时,我想从我的服务器获取数据,这是我通过 useEffect 所做的并将其显示在屏幕上(数据是电子邮件列表)....然后有添加 email 按钮..当用户点击它时我通过 EmailModal usestate 处理的弹出 Modal () 出现...在弹出窗口中,用户可以添加新的 email 和 onclick 提交按钮,email 将发送到服务器...弹出窗口关闭,屏幕应该使用这个新的 email 进行更新连同之前的 email

There are two problem which I am not able to solve 1 when I click on submit, the screen does not rerenders and show the updated list 2 When I am typing in Modal(popup) to add email it is blinking ( I think it is rerendering on each letter type..有两个我无法解决的问题 1 当我点击提交时,屏幕不会重新呈现并显示更新的列表 2 当我输入 Modal(popup) 以添加 email 时,它在闪烁(我认为它正在重新呈现在每个字母类型..

I am not able to solve this...Any help would be appreciated..Thank you in advanced ( if possible please show the correct way of implementing this)我无法解决这个问题...任何帮助将不胜感激..先谢谢你(如果可能请展示正确的实现方式)

const Patent = () => {

  const xx = [];
  
  const [EmailModal, setEmailModal] = useState(false);

  const changeState1 = () => {  
     
      xx.push(
      <Card
      title= {typemail}
     asset={<img width="24" height="24" src="/assets/settings/email.svg" alt="" />} />
     )
   
   
    const requestOptions = {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "jijfijwijfijfisjifffsNDc0MjY0NzAsImsdsddI3MCwicmxsdddadfAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
          body: JSON.stringify({"firebase_id":"fasasgOtg1","sender_email":typemail})
    };
     
          fetch('https://demo.car.com/aura/em/li', requestOptions)
          .then(response => response.json())
          .then(data =>  console.log(data));    
  
  

      setvr(xx);
     setEmailModal(false)

 }; 


  const Frapper = ({ tit, subtit, child }) => (
    <div className={styles.frapper}>
      <div className={styles.contain}>
      <h4 className={styles.tit}>{tit}</h4>
      <Button
        className={styles.btn12}
        onClick={() => setEmailModal(true)}      
      > {'+ Add Email'} </Button> 
      </div>    
      <h7 className={styles.subtitle}>{subtitle}</h7>
      {children}
    </div>
  )
    
   const [typemail, settypemail] = useState("");
   const [fruits, setFruits] = useState([]);
   const [vr,setvr] = useState([]);

   useEffect(() => {
   
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "asdaijdcisjciASDASDADAcCI6MTY0ODAzMTI3MCwicm9sZSI6ImV4cGVydCJ9.6pYrAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
        body: JSON.stringify({"firebase_id":"MgOtg1"})
    };
   
        fetch('https://demo.car.com/aura/em/li', requestOptions)
        .then(response => response.json()) 
        .then(data => setFruits(data.success));    
   
   }, []);

  

   for(let i = 0;i<fruits.length;i++){
     xx.push(
      <Card title= {fruits[i].SenderEmail}  status={fruits[i].Status} asset={<img width="24" height="24" src="/assets/settings/email.svg" alt="" />} />,

      );
   }
    
  useEffect(() => {
     
  }, [xx]);

      return (
        <>
          <Frapper tit="Emails"  subtitle="Authenticate emails">
            <div className={styles.integrationContainer}>
              <div className={styles.frapper}>
              {xx.map(data => (
                <div>{data}</div>
              ))}
              
           <Modal
          visible={showEmailModal}
         
          footer={null}
          onCancel={() => setEmailModal(false)}
          style={{ overflow: "hidden", borderRadius: "15px", padding: "0px", height: "300px" }}
        >
          <h7 className={styles.modalTitle}>New Email</h7>
          <CustomInput 
        placeholder="Enter your Email Address"
        onChange={settypemail}
        value={typemail}
        style={{ maxWidth: "700px", margin: "30px 0px 20px 0px" }} />

        <Button
        className={styles.btn}
        onClick={changeState1}   
      > {'Submit'} </Button>                
          <div className={`${styles.row} ${styles.alignEnd}`}>       
          </div>
        </Modal>                       
         </div>
         </div>
          </Frapper>
         
      </>
      );
  
}

I am not sure if this will fix your issue, but since you are not allowed to mutate the state directly (this is a React-specific thing), you cannot .push onto the state array directly.我不确定这是否会解决您的问题,但是由于不允许您直接改变 state(这是特定于 React 的东西),因此您不能直接将.push到 state 数组上。 When dealing with states that are arrays, you should use the destructuring syntax to add new element.在处理状态为 arrays 时,您应该使用解构语法来添加新元素。

More info can be read here: https://javascript.plainenglish.io/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc更多信息可以在这里阅读: https://javascript.plainenglish.io/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

Can you try this你能试试这个吗

const changeState1 = () => {  
    const requestOptions = {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + "jijfijwijfijfisjifffsNDc0MjY0NzAsImsdsddI3MCwicmxsdddadfAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
          body: JSON.stringify({"firebase_id":"fasasgOtg1","sender_email":typemail})
    };
     
    fetch('https://demo.car.com/aura/em/li', requestOptions)
        .then(response => response.json())
        .then(data =>  console.log(data));    
  
  
     const newElement = (
       <Card
         title= {typemail}
         asset={<img
                  width="24"
                  height="24"
                  src="/assets/settings/email.svg" alt=""
                 />}
       />
     )
     // Update state using array destructuring syntax
     setvr(curr => [...curr, newElement]);
     setEmailModal(false)

 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM