Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/475.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 如何根据页面url更改背景?_Javascript_Css_Reactjs_React Router - Fatal编程技术网

Javascript 如何根据页面url更改背景?

Javascript 如何根据页面url更改背景?,javascript,css,reactjs,react-router,Javascript,Css,Reactjs,React Router,我有一个有几个页面的简单应用程序,现在我想根据页面URL更改背景颜色 使用react js 期望什么 当路径名为/movies时,我想将背景更改为红色 这是我到目前为止所拥有的 import React from 'react' function Testing() { const[moviesUrlBackgroundColor, setMoviesUrlBackgroundColor] = useState('green'); const getMoviesUrl = window.

我有一个有几个页面的简单应用程序,现在我想根据页面URL更改背景颜色 使用react js

期望什么

当路径名为
/movies
时,我想将背景更改为红色

这是我到目前为止所拥有的

 import React from 'react'

function Testing() {
const[moviesUrlBackgroundColor, setMoviesUrlBackgroundColor] = useState('green');


const getMoviesUrl = window.location.pathname;


if(getMoviesUrl == '/movies'){
    setMoviesUrlBackgroundColor('red');
}else{
    setMoviesUrlBackgroundColor('green');
}

    return (
        <div>
            <Container style={{backgroundColor:moviesUrlBackgroundColor}}>
            
                Testing
            </Container>
        </div>
    )
}

export default Testing

const Container = styled.div`
    background-color:green
`;

我需要做什么才能工作?

您应该进行额外检查,以确保您是否设置了背景色。您当前的代码正在导致重新加载程序中断时间

 import React from 'react'

 function Testing() {
 const[moviesUrlBackgroundColor, setMoviesUrlBackgroundColor] = useState('green');
 const [bgFlag, setbgFlag] = useState(false);


 const getMoviesUrl = window.location.pathname;

 if(!bgFlag){
     setMoviesUrlBackgroundColor(getMoviesUrl == '/movies' ? 'red' : 'green')
     setbgFlag(true)
 }

return (
    <div>
        <Container style={{backgroundColor:moviesUrlBackgroundColor}}>
        
            Testing
        </Container>
    </div>
)
 }

 export default Testing

const Container = styled.div`
    background-color:green
`;
从“React”导入React
功能测试(){
const[moviesUrlBackgroundColor,setMoviesUrlBackgroundColor]=useState('green');
const[bgFlag,setbgFlag]=useState(false);
const getMoviesUrl=window.location.pathname;
如果(!bgFlag){
setMoviesUrlBackgroundColor(getMoviesUrl=='/movies'?'red':'green')
setbgFlag(真)
}
返回(
测试
)
}
导出默认测试
const Container=styled.div`
背景颜色:绿色
`;

使用
useffect
块,以便有效地执行副作用

  useEffect(() => {
    if(getMoviesUrl === '/movies'){
      console.log("running")
        setMoviesUrlBackgroundColor('red');
    }else{
        setMoviesUrlBackgroundColor('green');
    }
  },[getMoviesUrl]);

问题是调用
setMoviesUrlBackgroundColor
时没有使用
效果
包装,这会导致递归调用

为了解决此问题,您只需根据需要简单设置状态。在本例中,您的路径名已更改:

React.useffect(()=>{
如果(getMoviesUrl=='/movies'){
setMoviesUrlBackgroundColor(“红色”);
}否则{
setMoviesUrlBackgroundColor(“绿色”);
}
},[getMoviesUrl])

好的,我想我明白了,您在第一条if语句中创建了一个无限循环:

if (getMoviesUrl == '/movies') {
    // every time you change state, that causes your component
    // to re-render, and when it re-renders again you're checking
    // changing your state AGAIN, so it's an infinite loop
    setMoviesUrlBackgroundColor('red');
}

我建议对此使用react route并从参数获取url,然后在组件首次装载时更新componentDidMount或useEffect hook上的背景色,以防止无限循环。

Window.location.pathname正在重置每个渲染的状态,因此,需要将其放置在
useffect
挂钩中,以防止重新渲染

此外,这将是一个很好的用例,可以将
props
传递给您的样式化组件。 也包括在下面的代码中

这里有一个指向我用该解决方案制作的代码沙盒的链接。

import React,{useState,useffect}来自“React”;
从“样式化组件”导入样式化;
const Container=styled.div`
背景:${(道具)=>props.backgroundColor | |“绿色”};
`;
常数测试=()=>{
const[moviesUrlBackgroundColor,setMoviesUrlBackgroundColor]=useState(
“绿色”
);
useffect(()=>{
const getMoviesUrl=window.location.pathname;
如果(getMoviesUrl==“/movies”){
setMoviesUrlBackgroundColor(“黄色”);
}
},[moviesUrlBackgroundColor];
返回(
试验
);
};
导出默认测试;

干杯

但现在我需要刷新以查看更改,如果用户导航到另一个页面URL,在我刷新页面之前,它仍然是相同的,然后你需要使用更高阶的组件,在其中传递位置,一旦道具更改,你就更改背景不幸的是,如果我刷新页面,我将用户导航到另一个页面URL,它的颜色还是一样的,当时的url是什么样子的?例如
http://127.0.0.1:8001/templates
或“我不确定是否正确,因为你说颜色还是一样的。”。它是红色的还是绿色的?它应该是绿色的,因为路径是
movies
only:)如果路径是/movies/b颜色是红色或绿色,它只需要根据该路径更改颜色,但在刷新页面时会工作不幸的是,如果我刷新页面,我用户导航到另一个页面url,颜色仍然相同,不幸的是,如果我刷新页面,当用户导航到另一个页面URL时,颜色是否仍然相同?
if (getMoviesUrl == '/movies') {
    // every time you change state, that causes your component
    // to re-render, and when it re-renders again you're checking
    // changing your state AGAIN, so it's an infinite loop
    setMoviesUrlBackgroundColor('red');
}