反应:重新加载页面不再获取数据

时间:2020-06-11 07:58:07

标签: javascript reactjs components

当我在主页上并单击“课程”组件时,将加载课程页面,从url获取课程ID,并从本地js文件获取数据以填充课程页面。好吧,只有当我从主页上单击时,才会发生这种情况。但是,当我已经在课程页面上填充了数据并重新加载页面时,我从URL中获取ID,但是这次数据显示为“未定义” ...我不明白为什么它不使用数据是否像以前一样?

这是我的组件实现:

 const Lesson = () => {
  const { id } = useParams();
  const [lesson, setLesson] = useState(getLesson(id));

  console.log("id: ", id);
  console.log("lesson: ", lesson);

  return (...);
};

当我从主页上单击课程组件时,这里是控制台: the console when it works

当我简单地重新加载课程页面时,有一个控制台:the console when it doesn't work

我尝试将useEffect()与内部的setLesson(getLesson(id))一起使用,但没有任何变化...

我也尝试过:

 if (id) lesson = getLesson(id);

但同样,它不起作用...:(

getLesson()从这个名为fakeLessonsService.js的文件中获取数据:

 import getHipHopLessons from "./hipHopLessons";

 const lessons = [...getHipHopLessons()];

 export function getLesson(lessonId) {
    return lessons.find((lesson) => lesson._id === lessonId);
 }

文件“ ./hipHopLessons”仅返回课程对象数组。

getLesson()仅在此页面上加载。

1 个答案:

答案 0 :(得分:0)

useState的参数仅在初始渲染时使用。

如果ID更改,则应使用useEffect更新状态

namespace App\Service;

use App\Utils\Utils;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;

class MailService
{
    private $mailer;

    /**
     * MailService constructor.
     *
     * @param $mailer
     */
    public function __construct(MailerInterface $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * @param string $renderedView
     * @param string $adresse
     * @param string $subject
     *
     * @throws TransportExceptionInterface
     * here $renderedview is a a twig template i used to generate my email html
     */
    public function sendMail(string $renderedView, string $adresse, string $subject, string $env)
    {
        if ('dev' !== $env) {
            $email = (new Email())
                ->from(your@email.com)
                ->to($adresse)
                ->subject($subject)
                ->html($renderedView);

            $this->mailer->send($email);
        }
    }
}

PS。确保const [lesson, setLesson] = useState({}); useEffect(() => { getLesson(id).then(val => setLesson(val)); }, [id]); 不是异步

如果它是异步的,那么您必须编写类似的代码

getHipHopLessons