如何在我的组件中使用 Redux 传递此初始状态值?

huangapple go评论86阅读模式
英文:

How do I pass this initial state value using redux in my component?

问题

我正在使用[multer][1]来处理上传到我的Next.js应用的图像而且我正在使用[Redux][2]来进行状态管理...

话虽如此我在我的存储中创建了一个名为`userAvatar`的属性用于最终在我的个人资料页面上设置头像

我注意到尽管使用了`mapStateToProps``userAvatar`未显示在`Profile`组件的props中从而导致图像无法持久保存

**没有**`userAvatar` prop
[![在这里输入图片描述][3]][3]

这是我的个人资料组件

```jsx
import { Button, Card, Feed, Icon, Image, Segment, Grid, Divider, Container, Header } from 'semantic-ui-react';
import MyHeader from '../Header/Header.jsx';
import ImageUploader from '../ImageUploader/ImageUploader.jsx';
import React, { useState } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { modalStateOn, modalStateOff } from '../../store/reducers/ui/index';
import { loadAvatar } from '../../store/reducers/users/index';

const ProfilePage = ({ history, isMobileFromSSR, userAvatar, ...props }) => {

  function handleImageUpload() {
    setProfileImage(true);
  }

  return (
    <>
      {console.log("userAvatar ", userAvatar)}
      {console.log('Profile Page!! ', props)}
      <Grid container columns={1} relaxed stackable>
        <Grid.Column>
          <MyHeader as='h2' content='Foo' textAlign='left' />
        </Grid.Column>
      </Grid>

      <Grid container columns={2} divided relaxed stackable>
        <Grid.Column>
          <Segment>
            <Card fluid>
              <Image src='static/profile-avatars/charly_desktop.jpg' wrapped ui={false} />
              <ImageUploader userAvatar={userAvatar} history={history} />
              <Card.Content>
                <Card.Header>Charly</Card.Header>
                <Card.Meta>
                  <span className='date'>Joined in 2015</span>
                </Card.Meta>
                <Card.Description>
                  Charly
                </Card.Description>
              </Card.Content>
              <Card.Content extra>
                <a>
                  <Icon name='user' />
                  22 Friends
                </a>
              </Card.Content>
            </Card>
          </Segment>
        </Grid.Column>
      </Grid>
    </>
  )
}

function mapStateToProps(state) {
  const { ui, users } = state;
  const { isLoggedIn, userAvatar } = users;
  const { modalActive } = ui;

  return { isLoggedIn, userAvatar, modalActive };
}

const mapDispatchToProps = dispatch =>
  bindActionCreators({ modalStateOn, modalStateOff, loadAvatar }, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(ProfilePage);

这是我认为它在某个地方未正确传递的原因。

这些是链中较高的组件。在从移动设备切换到桌面设备和反之时,上传的图像会恢复为默认图像。

const LinkNavWithLayout = ({ children, history, data, userAvatar, modalActive, modalStateOn, modalStateOff, isLoggedIn }) => (
  <React.Fragment>
    <DesktopContainer history={history} data={data} userAvatar={userAvatar} modalActive={modalActive} modalStateOn={modalStateOn} modalStateOff={modalStateOff} isLoggedIn={isLoggedIn}>
      {children}
    </DesktopContainer>
    <MobileContainer history={history} data={data} userAvatar={userAvatar} modalActive={modalActive} modalStateOn={modalStateOn} modalStateOff={modalStateOff} isLoggedIn={isLoggedIn}>
      {children}
    </MobileContainer>
  </React.Fragment>
);

以下是路由:

<>
  <Switch>
    <Route
      path='/'
      isLoggedIn={isLoggedIn}
      exact
      render={(props) => <LinkNavWithLayout {...props} data={navBars}><Index /></LinkNavWithLayout>} />
    <PrivateRoute
      path='/profile'
      isLoggedIn={isLoggedIn}>
      <LinkNavWithLayout data={navBars}><Profile user/></LinkNavWithLayout>
    </PrivateRoute>
    <PrivateRoute
      path='/dashboard'
      isLoggedIn={isLoggedIn}>
      <LinkNavWithLayout data={navBars}><Dashboard /></LinkNavWithLayout>
    </PrivateRoute>
    <Route
      path='/login'
      render={(props) => <Login {...props}/>}
    />
    <Route
      path='/register'
      render={(props) => <Register {...props}/>}
    />
    <Route component={({ location }) => <p>Sorry but the page <h1>{location.pathname.substring(1)} </h1> Page, Could Not be found</p>} />
  </Switch>
</>

那么在哪里应该添加userAvatar prop以在整个应用中渲染头像。
感谢您的任何建议!!!


<details>
<summary>英文:</summary>
I am using [multer][1] to handle image uploads to my Next.js app. And I&#39;m using [Redux][2] for state management...
That being said, I created a property in my store called `userAvatar` for an eventual avatar for my profile page. 
I noticed despite using `mapStateToProps`, `userAvatar` is not showing amongst the props of the `Profile` component and thus resulting in the image not persisting.
**NO** `userAvatar` prop!
[![enter image description here][3]][3]
Here is my profile component:
import { Button, Card, Feed, Icon, Image, Segment, Grid, Divider, Container, Header } from &#39;semantic-ui-react&#39;
import MyHeader from &#39;../Header/Header.jsx&#39;
import ImageUploader from &#39;../ImageUploader/ImageUploader.jsx&#39;;
import React, { useState } from &#39;react&#39;;
import { connect } from &#39;react-redux&#39;
import { bindActionCreators } from &#39;redux&#39;
import { modalStateOn, modalStateOff } from &#39;../../store/reducers/ui/index&#39;
import { loadAvatar } from &#39;../../store/reducers/users/index&#39;
const ProfilePage = ({ history, isMobileFromSSR, userAvatar,...props }) =&gt; {
function handleImageUpload() {
setProfileImage(true);
}
return (
&lt;&gt;
{console.log(&quot;userAvatar &quot;, userAvatar)}
{console.log(&#39;Profile Page!! &#39;, props)}
&lt;Grid container columns={1} relaxed stackable&gt;
&lt;Grid.Column&gt;
&lt;MyHeader as=&#39;h2&#39; content=&#39;Foo&#39; textAlign=&#39;left&#39; /&gt;
&lt;/Grid.Column&gt;
&lt;/Grid&gt;
&lt;Grid container columns={2} divided relaxed stackable&gt;
&lt;Grid.Column&gt;
&lt;Segment&gt;
&lt;Card fluid&gt;
&lt;Image src=&#39;static/profile-avatars/charly_desktop.jpg&#39; wrapped ui={false} /&gt;
&lt;ImageUploader userAvatar={userAvatar} history={history} /&gt;
&lt;Card.Content&gt;
&lt;Card.Header&gt;Charly&lt;/Card.Header&gt;
&lt;Card.Meta&gt;
&lt;span className=&#39;date&#39;&gt;Joined in 2015&lt;/span&gt;
&lt;/Card.Meta&gt;
&lt;Card.Description&gt;
Charly
&lt;/Card.Description&gt;
&lt;/Card.Content&gt;
&lt;Card.Content extra&gt;
&lt;a&gt;
&lt;Icon name=&#39;user&#39; /&gt;
22 Friends
&lt;/a&gt;
&lt;/Card.Content&gt;
&lt;/Card&gt;
&lt;/Segment&gt;
&lt;/Grid.Column&gt;
&lt;/Grid&gt;
&lt;/&gt;
)
}
function mapStateToProps(state) {
const { ui, users } = state
const { isLoggedIn, userAvatar } = users
const { modalActive } = ui
return { isLoggedIn, userAvatar, modalActive }
}
const mapDispatchToProps = dispatch =&gt;
bindActionCreators({ modalStateOn, modalStateOff, loadAvatar }, dispatch)
export default connect(mapStateToProps, mapDispatchToProps)(ProfilePage)
My thinking this is because its not getting passed in correctly somewhere.
These are the components which are higher in the chain. The uploaded reverts to the default when changing from mobile to desktop and vice-versa.
const LinkNavWithLayout = ({ children, history, data, userAvatar, modalActive, modalStateOn, modalStateOff, isLoggedIn }) =&gt; (
&lt;React.Fragment&gt;
&lt;DesktopContainer history={history} data={data} userAvatar={userAvatar} modalActive={modalActive} modalStateOn={modalStateOn} modalStateOff={modalStateOff} isLoggedIn={isLoggedIn}&gt;
{children}
&lt;/DesktopContainer&gt;
&lt;MobileContainer history={history} data={data} userAvatar={userAvatar} modalActive={modalActive} modalStateOn={modalStateOn} modalStateOff={modalStateOff} isLoggedIn={isLoggedIn}&gt;
{children}
&lt;/MobileContainer&gt;
&lt;/React.Fragment&gt;
)
And these are the routes:
&lt;&gt;
&lt;Switch&gt;
&lt;Route
path=&#39;/&#39;
isLoggedIn={isLoggedIn}
exact
render={(props) =&gt; &lt;LinkNavWithLayout {...props} data={navBars}&gt;&lt;Index /&gt;&lt;/LinkNavWithLayout&gt;} /&gt;
&lt;PrivateRoute
path=&#39;/profile&#39;
isLoggedIn={isLoggedIn}
&gt;
&lt;LinkNavWithLayout data={navBars}&gt;&lt;Profile user/&gt;&lt;/LinkNavWithLayout&gt;
&lt;/PrivateRoute&gt;
&lt;PrivateRoute
path=&#39;/dashboard&#39;
isLoggedIn={isLoggedIn}
&gt;
&lt;LinkNavWithLayout data={navBars}&gt;&lt;Dashboard /&gt;&lt;/LinkNavWithLayout&gt;
&lt;/PrivateRoute&gt;
&lt;Route
path=&#39;/login&#39;
render={(props) =&gt; &lt;Login {...props}/&gt;}
/&gt;
&lt;Route
path=&#39;/register&#39;
render={(props) =&gt; &lt;Register {...props}/&gt;}
/&gt;
&lt;Route component={({ location }) =&gt; &lt;p&gt;Sorry but the page &lt;h1&gt;{location.pathname.substring(1)} &lt;/h1&gt; Page, Could Not be found&lt;/p&gt;} /&gt;
&lt;/Switch&gt;
&lt;/&gt;
So where is should I be adding the `userAvatar` prop to make the avatar render across my app.
Thank you for any input!!!
[1]: https://www.npmjs.com/package/multer
[2]: https://redux.js.org/
[3]: https://i.stack.imgur.com/WkE6t.png
</details>
# 答案1
**得分**: 1
在这里,你使用了 `const ProfilePage = ({ history, isMobileFromSSR, userAvatar,...props }) => {` 的语法,将 `userAvatar` 分配给了它自己的变量,使用了 `rest` 语法,这意味着它不会包含在 `props` 对象中。
你的控制台日志显示 `userAvatar` 具有正确的值作为 `userAvatar`。
如果你希望它放在 `props` 对象中,只需从函数声明中移除它,像这样: `({ history, isMobileFromSSR,...props })`。
这里是有关[rest参数](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)的文档链接。以下是最相关的部分:
> rest参数只是那些没有被赋予单独名称的参数(即在函数表达式中没有正式定义的参数)。
<details>
<summary>英文:</summary>
Here `const ProfilePage = ({ history, isMobileFromSSR, userAvatar,...props }) =&gt; {` you assigned `userAvatar` to its own variable with the `rest` syntax which means it will not be included in the `props` object. 
Your console log appears to show it having a correct value as `userAvatar`. 
If you want it to be in the `props` object instead, just remove it from your function declaration like this: `({ history, isMobileFromSSR,...props })`.
Here is a link to the 
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) on rest parameters. Here is the most relevant piece: &gt;rest parameters are only the ones that haven&#39;t been given a separate name (i.e. formally defined in function expression) </details>

huangapple
  • 本文由 发表于 2020年1月4日 01:08:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定