>  기사  >  웹 프론트엔드  >  React+antd는 백그라운드 관리 시스템을 만듭니다.

React+antd는 백그라운드 관리 시스템을 만듭니다.

php中世界最好的语言
php中世界最好的语言원래의
2018-06-05 15:25:265206검색

이번에는 백엔드 관리 시스템인 React+antd를 소개하겠습니다. 백엔드 관리 시스템인 React+antd에 대한 주의 사항은 무엇인가요? 다음은 실제 사례입니다.

create-react-app 스캐폴딩 사용

구체적인 기본 구성은

antd 구성 요소로 구현된 관리 시스템 데모, 온라인 주소

개발 전 반영

1을 참조하세요. import는 동적으로 로드된 모듈의 함수인 import(매개변수)이고, 매개변수는 모듈 주소입니다.

참고: 가져오기 후에 Promise 객체가 반환됩니다.

import('/components/chart').then(mud => {
  dosomething(mod)
});
이 데모는 비동기 로딩 구성 요소 번들을 빌드합니다. 특정 코드에 대해서는

class Bundle extends Component {
 constructor(props) {
   super(props);
   this.state = {
     mod: null
   };
 }
 unmount = false
 componentDidMount = () => {
  // 加载组件时,打开全局loading
  this.props.dispatch(loading(true))
  this.load(this.props)
 }
 componentWillUnmount = () => {
  this.unmount = true
 }
 
 componentWillReceiveProps(nextProps) {
   if (nextProps.load !== this.props.load) {
     this.load(nextProps)
   }
 }
 load(props) {
   if (this.state.mod) {
     return true
   }
   //注意这里,使用Promise对象; mod.default导出默认
   props.load().then((mod) => {
     if (this.unmount) {
       // 离开组件时,不异步执行setState
       this.props.dispatch(loading(false))
       return false
     }
     this.setState({
       mod: mod.default ? mod.default : mod
     }, _ => {
      // 组件加载完毕,关闭loading
      this.props.dispatch(loading(false))
     });
   });
 }
 render() {
   return this.state.mod ? this.props.children(this.state.mod) : null;
 }
}
구체적인 사용법을 참조하세요.

<Bundle load={() => import('路径')}>
  {Comp => {
   return Comp ? <Comp /> : <p>加载中...</p>
  }}
 </Bundle>

2 전역 로딩

은 redux와 협력합니다. 디스패치 => 리듀서 업데이트 => mapstate 업데이트. 렌더링을 로드하려면

자세한 내용은 이 데모 주소 src/routers/router.js - render function

3을 참조하세요. 라우팅 객체를 구성하세요

프로젝트 레이아웃은 다음과 같습니다

이것 데모는 공식 router4를 사용합니다. 문서 데모는 단일 라인 경로(예: Vue 라우터)이며 통합 구성 개체가 없습니다. 관리 시스템은 기본적으로 비즈니스 개발을 위한 콘텐츠를 중심으로 이루어집니다. 공통 구성을 구축하면 router.config.js

const routers = [
 {
  menuName: '主页',
  menuIco: 'home',
  component: 'home/home.js', // 主页
  path: '/admin/home' // 主页
 },
 {
  menuName: '用户',
  menuIco: 'user',
  children: [
   {
    menuName: '用户列表',
    component: 'user/list.js', // 主页
    path: '/admin/user/list' // 主页
   }
  ]
 },
 {
  menuName: '多级菜单',
  menuIco: 'setting',
  children: [
   {
    menuName: '多级菜单2',
    children: [
     {
      menuName: '菜单',
      component: 'user/list.js', // 主页
      path: '/admin/user/list3' // 主页
     }
    ]
   }
  ]
 },
 {
  menuName: '关于我',
  menuIco: 'smile-o',
  component: 'about/about.js', // 主页
  path: '/admin/about' // 主页
 }
]
구현 아이디어를 개발하고 구축하는 데 도움이 됩니다. 가장 바깥쪽 레이아웃은 Admin이고 콘텐츠는 Admin에 의해 래핑됩니다. .children. 내용을 내용에 입력합니다. (번들 컴포넌트를 비동기적으로 로드한 후 렌더링을 위해 컴포넌트에 삽입)

<Admin>
  <Content { ...this.props } breadcrumb={this.state.breadcrumb}>
    {this.props.children}
  </Content>
</Admin>
// Content组件内部
render() {
  return (
    <p> 
      {this.props.children}
    </p>
  )
}
// 本demo实现,详见src/routers/router.js
<Route
 path="/admin"
 render={item => (
  <Admin {...item} { ...this.props }>
   {initRouters.map(el => this.deepItem(el, { ...this.props, ...item}))}
  </Admin>
 )}
/>

4. 일반 리듀서 구성

비즈니스 시나리오의 일부 컴포넌트는 상태 개선이 필요합니다. 상태 개선을 이해하려면 과학적으로 온라인에 접속하세요)

import otherReducers from './otherReducers'
const App = combineReducers({
  rootReducers,
  ...otherReducers // 其他需要增加的reducers
})

5. 로그인 확인

페이지 리디렉션 시 실행되는 withRouter 기능을 사용하세요

const newWithRouter = withRouter(props => {
  // ....
})
로그인하지 않으면 반환됩니다

return <Redirect to="/login" />

6. 경로 차단

위와 동일하게 라우팅 구성 및 권한에 따라 해당 메뉴로 돌아가거나

return <Redirect to={其他} />

7 기타 구성

7-1. 사용자 정의 스타일

// 修改webpack.config.dev.js 和 webpack.config-prod.js 配置文件
{
  test: /\.(css|less)$/,
  // 匹配src的都自动加载css-module
  include: [/src/],
  exclude: [/theme/],
  use: [
    require.resolve('style-loader'), {
      loader: require.resolve('css-loader'),
      options: {
        importLoaders: 1,
        modules: true, // 新增对css modules的支持
        localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
      }
    }, {
      loader: require.resolve('postcss-loader'),
      options: {
        // Necessary for external CSS imports to work
        // https://github.com/facebookincubator/create-react-app/issues/2677
        ident: 'postcss',
        plugins: () => [
          require('postcss-flexbugs-fixes'),
          autoprefixer({
            browsers: [
              '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9&#39;, // React doesn&#39;t support IE8 anyway
            ],
            flexbox: &#39;no-2009&#39;
          })
        ]
      }
    }, {
      loader: require.resolve(&#39;less-loader&#39;) // compiles Less to CSS
    }
  ]
}, {
  // 不匹配node_modules,theme的都不能自动加载css-module
  test: /\.(css|less)$/,
  include: [/node_modules/,/theme/],
  use: [
    {
      loader: "style-loader"
    }, {
      loader: "css-loader",
      options: {
        importLoaders: 1
      }
    }, {
      loader: require.resolve(&#39;less-loader&#39;) // compiles Less to CSS
    }
  ]
},

사용법: 직접 가져오기

App.js의

import &#39;./assets/theme/App.less&#39;

7-2. 핫 업데이트

1단계:

// 安装react-hot-loader 
npm install --save-dev react-hot-loader

2단계:

webpack.config.js의 항목 값에 React-hot-loader/patch를 추가합니다.

3단계:

webpackDevServer.config.js에서 hot을 true로 설정

4단계: webpack.config.dev.js에서 babel-loader 플러그인에 React-hot-loader/babel을 추가합니다

{
  test: /\.(js|jsx|mjs)$/,
  include: paths.appSrc,
  loader: require.resolve(&#39;babel-loader&#39;),
  options: {
    // This is a feature of `babel-loader` for webpack (not Babel itself). It
    // enables caching results in ./node_modules/.cache/babel-loader/ directory for
    // faster rebuilds.
    cacheDirectory: true,
    plugins: [
      &#39;react-hot-loader/babel&#39;
    ]
  }
},

5단계:

index.js 다시 작성 , 앱 마운트

import { AppContainer } from &#39;react-hot-loader&#39;
const render = Component => {
  ReactDOM.render(
    <AppContainer>
      <Component></Component>
    </AppContainer>,
    document.getElementById('root')
  )
}
render(App)
if(module.hot) {
  module.hot.accept('./App',() => {
    render(App);
  });
}
7-3. 로컬 탐색

package.json에

homepage:'.'
Postscript 직접 추가: React 및 vue

react 사용에 대한 통찰력은 코드 난이도, 학습 곡선, 허식 지수 및 커뮤니티가 포함된 함수형 프로그래밍입니다. vue보다 생태학적 다양성이 더 높습니다.

vue는 개발의 어려움을 줄이기 위해 많은 지침을 제공하며 상세하고 완전한 문서를 통해 더 빠르게 시작할 수 있습니다.

react는 vue의 지침에 비해 더 적은 수의 API를 제공하므로 비즈니스 시나리오의 기능을 직접 구현해야 하기 때문에 더 어렵습니다.

vue는 중소 규모 프로젝트에 적합하며 단일 사용자로 빠르게 개발할 수 있습니다.

react는 대규모 프로젝트에 적합합니다.

이 기사의 사례를 읽으신 후 해당 방법을 익히셨을 것이라 생각합니다. 더 흥미로운 정보는 다른 관련 기사를 참조하세요. PHP 중국어 웹사이트에서!

추천도서:

패키징 파일 경로 구성 오류 해결 방법


제목 텍스트 클릭 시 글꼴 전환 효과 만드는 방법

위 내용은 React+antd는 백그라운드 관리 시스템을 만듭니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.