react及Redux<一>
编辑时间:2021-10-09 作者:金满斗 浏览量:1306 来源:原创

react  使用三元表达式进行条件渲染

代码编辑器在 CheckUserAge 组件的 render() 方法中定义了三个常量, 它们分别是 buttonOne、buttonTwo 和 buttonThree。 每个都分配了一个表示按钮元素的简单 JSX 表达式。 首先,使用 input 和 userAge 初始化 CheckUserAge 的 state,并将其值设置为空字符串。
一旦组件将信息渲染给页面,用户应该有一种方法与之交互。 在组件的 return 语句中,设置一个实现以下逻辑的三元表达式:当页面首次加载时,将提交按钮 buttonOne 渲染到页面。 然后,当用户输入年龄并点击该按钮时,根据年龄渲染不同的按钮。 如果用户输入的数字小于18,则渲染buttonThree。 如果用户输入的数字大于或等于18,则渲染buttonTwo。
例子:
const inputStyle = {
  width: 235,
  margin: 5
};

class CheckUserAge extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      input:"",
      userAge: ''
    }
    this.submit = this.submit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(e) {
    this.setState({
      input: e.target.value,
      userAge: ''
    });
  }
  submit() {
    this.setState(state => ({
      userAge: state.input
    }));
  }
  render() {
    const buttonOne = <button onClick={this.submit}>Submit</button>;
    const buttonTwo = <button>You May Enter</button>;
    const buttonThree = <button>You Shall Not Pass</button>;
    return (
      <div>
        <h3>Enter Your Age to Continue</h3>
        <input
          style={inputStyle}
          type='number'
          value={this.state.input}
          onChange={this.handleChange}
        />
        <br />
       {this.state.userAge=="" ?buttonOne:(this.state.userAge>=18) ? buttonTwo : buttonThree}
      </div>
    );
  }
}

根据pr有条件的渲染

class Results extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h1>{this.props.fiftyFifty?"You Win!":"You Lose!"}</h1>;
    
  }
}

class GameOfChance extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 1
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState(prevState => {
      return {
        counter: prevState.counter+1
      }
    });
  }
  render() {
    const expression = (Math.random() >= .5); 
    return (
      <div>
        <button onClick={this.handleClick}>Play Again</button>
        <Results fiftyFifty={expression} />
        <p>{'Turn: ' + this.state.counter}</p>
      </div>
    );
  }
}

数组的过滤和显示
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [
        {
          username: 'Jeff',
          online: true
        },
        {
          username: 'Alan',
          online: false
        },
        {
          username: 'Mary',
          online: true
        },
        {
          username: 'Jim',
          online: false
        },
        {
          username: 'Sara',
          online: true
        },
        {
          username: 'Laura',
          online: true
        }
      ]
    };
  }
  render() {
    const usersOnline = this.state.users.filter(item=>item.online);
    const renderOnline = usersOnline.map((item,index)=><li key={index} >{item.username}</li>)
    return (
      <div>
        <h1>Current Online Users:</h1>
        <ul>{renderOnline}</ul>
      </div>
    );
  }
}


redux 初始

const reducer = (state = 5) => {
  return state;
}
const store= Redux.createStore(reducer);

从 Redux Store 获取状态
const store = Redux.createStore(
  (state = 5) => state
);
const currentState = store.getState();
console.log(currentState);

 state 是只读的。 换句话说,reducer 函数必须始终返回一个新的 state,并且永远不会直接修改状态。 
 const defaultState = {
  login: false
};

const reducer = (state = defaultState, action) => {
  if (action.type === 'LOGIN') {
     return {
      login: true
    };
  } 
 return state;
};

const store = Redux.createStore(reducer);
const loginAction = () => {
  return {
    type: 'LOGIN'
  }
};

进一步例子
const defaultState = {
  authenticated: false
};

const authReducer = (state = defaultState, action) => {
let nws={};
switch(action.type){
  case 'LOGIN':
    nws.authenticated = true;
    break;
  case 'LOGOUT':
    nws.authenticated = false;
    break;
  default:
    nws = state;
}
return nws;
};

const store = Redux.createStore(authReducer);

const loginUser = () => {
  return {
    type: 'LOGIN'
  }
};

const logoutUser = () => {
  return {
    type: 'LOGOUT'
  }
};

注册 Store 监听器
const ADD = 'ADD';

const reducer = (state = 0, action) => {
  switch(action.type) {
    case ADD:
      return state + 1;
    default:
      return state;
  }
};
const store = Redux.createStore(reducer);
let count = 0;
store.subscribe(()=>count++);
store.dispatch({type: ADD});
console.log(count);
store.dispatch({type: ADD});
console.log(count);
store.dispatch({type: ADD});
console.log(count);
组合多个 Reducers
例子:
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const counterReducer = (state = 0, action) => {
  switch(action.type) {
    case INCREMENT:
      return state + 1;
    case DECREMENT:
      return state - 1;
    default:
      return state;
  }
};
const LOGIN = 'LOGIN';
const LOGOUT = 'LOGOUT';
const authReducer = (state = {authenticated: false}, action) => {
  switch(action.type) {
    case LOGIN:
      return {
        authenticated: true
      }
    case LOGOUT:
      return {
        authenticated: false
      }
    default:
      return state;
  }
};

const rootReducer = Redux.combineReducers({
  count: counterReducer,
  auth: authReducer
});

const store = Redux.createStore(rootReducer);
发送 Action Data 给 Store
const ADD_NOTE = 'ADD_NOTE';

const notesReducer = (state = 'Initial State', action) => {
  switch(action.type) {
    case ADD_NOTE:
      return action.text;
    default:
      return state;
  }
};
const addNoteText = (note) => {
    return {type:ADD_NOTE,text:note}
};
const store = Redux.createStore(notesReducer);

console.log(store.getState());
store.dispatch(addNoteText('Hello!'));
console.log(store.getState());

来说两句吧