React使用useHistory跳转时提示style prop格式错误如何解决
React
style prop 映射格式报错问题解决 问题现象
React项目中原本运行正常的代码触发报错:The 'style' prop expects a mapping from style properties to values (Reactjs),报错栈指向路由跳转代码history.push("/mainpage")位置。
相关业务代码
function WelcomePage() { // 省略其他代码 const history = useHistory(); useEffect(() => { if(localStorage.getItem('currentUser')){ history.push("/mainPage") } }, []) function loginHandler(){ const ownerService = new OwnerService() const vetService = new VetService() if(selectedUserType==0){ ownerService.getByUsername(username).then(response=>{ const owner = response.data.data if(owner !=null ){ if(owner.password==password){ console.log(owner) dispatch(setCurrentUser(owner)) toast("başarıyla giriş yaptın") localStorage.setItem('currentUser', JSON.stringify(owner)) history.push("/mainpage") // 报错指向该行 } else{ toast("böyle bir kullanıcı bulunamadı") } }else{ toast("böyle bir kullanıcı bulunamadı") } }) } if(selectedUserType==1){ vetService.getByUsername(username).then(response=>{ const vet = response.data.data if(vet !=null ){ if(vet.password==password){ dispatch(setCurrentUser(vet)) toast("başarıyla giriş yaptın") localStorage.setItem('currentUser', JSON.stringify(vet)) history.push("/mainpage") } else{ toast("böyle bir kullanıcı bulunamadı") } }else{ toast("böyle bir kullanıcı bulunamadı") } }) } } return ( <div> // 省略渲染代码 </div> ); } export default WelcomePage;
报错信息
Unhandled Rejection (Error): The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX. (anonymous function) C:/Users/MithatAkbulut/Documents/GitHub/modules/Router.js:34 31 | if (!props.staticContext) { 32 | this.unlisten = props.history.listen(location => { 33 | if (this._isMounted) { > 34 | this.setState({ location }); | ^ 35 | } else { 36 | this._pendingLocation = location; 37 | } View compiled ▶ 7 stack frames were collapsed. (anonymous function) C:/Users/MithatAkbulut/Documents/GitHub/vetwebapp-react/src/pages/WelcomePage.jsx:56 53 | dispatch(setCurrentUser(owner)) 54 | toast("başarıyla giriş yaptın") 55 | localStorage.setItem('currentUser', JSON.stringify(owner)) > 56 | history.push("/mainpage") | ^ 57 | } 58 | else{ 59 | toast("böyle bir kullanıcı bulunamadı") View compiled
排查过程
最初怀疑是useHistory钩子存在问题,后续尝试删除所有localStorage相关代码复现问题,均未得到有效结论。报错信息提示问题和样式属性相关,但初步排查样式代码未发现异常。
根因定位
最终确认问题根源为跳转目标页面(mainpage)的style属性中使用了&&短路运算而非三元运算符:当条件为true时返回样式对象,运行正常;当条件为false时返回false布尔值,React无法识别该返回值作为样式属性,进而抛出错误。
不推荐写法
<button style={true&&{background:"red"}} >Button example</button>
上述写法在条件为false时会返回false,不符合React style属性要求的对象格式。
推荐写法
使用三元运算符兜底返回空样式对象或默认样式对象:
<button style={true?{background:"red"}:{background:"green"}} >Button example</button> <!-- 或兜底返回空对象 --> <button style={true?{background:"red"}:{}} >Button example</button>
内容的提问来源于stack exchange,提问作者user16969128
相关产品推荐
相关产品推荐

