Пересчитать функцию в созданном компоненте

$time_ago = ' ';
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',2592000 => 'month',604800 => 'week',86400 => 'day',3600 => 'hour',
60  => 'minute',1 => 'second');
foreach ($tokens as $unit => $text) {
if ($time < $unit)continue;
$numberOfUnits = floor($time / $unit);
$time_ago = ' '.$time_ago. $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').'  ';
$time = $time % $unit;}echo $time_ago;
1
задан RTW 12 March 2019 в 11:41
поделиться

1 ответ

Я почти уверен, что это связано с тем, как устанавливается searchBlock, поскольку похоже, что функция test ссылается на устаревшее значение (по умолчанию, в данном случае []) снова и снова.

Если вы переключитесь на следующий формат:

useEffect(() => {
    let tempBlock = (
      <button onClick={() => tagsSet((tags) => [ ...tags, { name: "x", description: "y" }])}
      >
        {
          "doesnt work. Its like test function with current values saved somewhere in momery"
        }
      </button>
    );
    searchBlockSet(tempBlock);
  }, []);

Он работает как положено.

Возможно, рассмотрите возможность перехода на следующий формат:

export default function Home() {
  const [tags, tagsSet] = useState([]);
  const [isSearchBlockVisible, setIsSearchBlockVisible] = useState(false);

  useEffect(() => setIsSearchBlockVisible(true), []);

  console.log(tags); // will give updated tags array here [{"name":"x","description":"y"}, ...and so on for every click]

  function test() {
    console.log(tags); // tags here will always be [], but should be [{"name":"x","description":"y"}, ...and so on for every click, after first click]
    let newTags = JSON.parse(JSON.stringify(tags));
    newTags.push({
      name: "x",
      description: "y"
    });
    tagsSet(newTags);
  }

  return (
    <div>
      <button onClick={test}>this works fine</button>
      {isSearchBlockVisible && (
        <button onClick={test}>
          {
            "doesnt work. Its like test function with current values saved somewhere in momery"
          }
        </button>
      )}
      {JSON.stringify(tags)}
    </div>
  );
}
0
ответ дан Powell Ye 12 March 2019 в 11:41
поделиться
Другие вопросы по тегам:

Похожие вопросы: