React之報(bào)錯(cuò)筆記及常見(jiàn)交互應(yīng)用(三)

總結(jié)了一些在react項(xiàng)目中遇到的問(wèn)題
1.和微信小程序一樣的push事件不能直接用
錯(cuò)誤:

      let newCart = this.state.shopcart.push(item);
        this.setState({shopcart:newCart});

正確:

      let newCart = this.state.shopcart;
        let newCartLen = newCart.length;
        newCart[newCartLen] = item;
        this.setState({shopcart:newCart});

2.react是單向數(shù)據(jù)流,所以這個(gè)用法是ok的
場(chǎng)景:點(diǎn)擊增加商品數(shù)量

render:
<span className="fa fa-plus item" onClick={this.addNum.bind(this,v.songNum)}></span>
fn:
 addNum(num,e){
        num+=1;
    }

3.input表單賦值
場(chǎng)景:購(gòu)物車數(shù)量隨在input框內(nèi)添數(shù)字改變

render:
 <input type="text" className="item" value={v.songNum} onChange={this.handleChange.bind(this,v)}/>{v.songNum}
Fn:
  handleChange(v,event) {
        v.songNum = parseFloat(event.target.value);
        this.setState({shopcart:this.state.shopcart});
    }

錯(cuò)誤:

render:
 <input type="text" className="item" value={v.songNum} onChange={this.handleChange.bind(this,v.songNum)}/>{v.songNum}
Fn:
  handleChange(v,event) {
        v = parseFloat(event.target.value);
        this.setState({shopcart:this.state.shopcart});
    }

4.多input表單處理


image.png
class Tableadd extends Component{
    constructor(props){
        super(props)
        this.state = {
            name:'',
            address:'',
            tel:''
        }
    }
    handleInputChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;
        this.setState({
            [name]: value
        });
        console.log(this.state);
    }

    handleChange(){

    }

    render(){
        return(
            <div className="form-container">
                <div className="group-row">
                    <span className="title">姓名:</span>
                    <div className="puton-item">
                        <input type="text" name="name" onChange={this.inputchange}/>
                    </div>
                </div>
                <div className="group-row">
                    <span className="title">愛(ài)好:</span>
                    <div className="puton-item">
                        <select value="lime" onChange={this.handleChange}>
                            <option value="grapefruit">Grapefruit</option>
                            <option value="lime">Lime</option>
                            <option value="coconut">Coconut</option>
                            <option value="mango">Mango</option>
                        </select>
                    </div>
                </div>
                <div className="group-row">
                    <span className="title">地址:</span>
                    <div className="puton-item">
                        <input type="text" name="address" onChange={this.inputchange}/>
                    </div>
                </div>
                <div className="group-row">
                    <span className="title">電話:</span>
                    <div className="puton-item">
                        <input type="text" name="tel" onChange={this.inputchange}/>
                    </div>
                </div>
            </div>
        )
    }
}


export default Tableadd;

當(dāng)然你也可以不用state定義變量,寫(xiě)在redux中直接取也可以的

5.es6箭頭函數(shù)

 componentDidMount(){
      this.timer = setInterval(()=>this.tick(),1000);
      console.log(this);
    }

為什么箭頭函數(shù)就可以直接在this函數(shù)中接著寫(xiě)this不報(bào)錯(cuò)呢?
箭頭函數(shù)的this定義:箭頭函數(shù)的this是在定義函數(shù)時(shí)綁定的,不是在執(zhí)行過(guò)程中綁定的。簡(jiǎn)單的說(shuō),函數(shù)在定義時(shí),this就繼承了定義函數(shù)的對(duì)象。
http://www.itdecent.cn/p/c1ee12a328d2

7.點(diǎn)擊,帶參點(diǎn)擊

<i className="plus iconfont icon-jiahao" onClick={this.addtocartFn(this, item)}></i>

這個(gè)方法在頁(yè)面加載之初就循環(huán)了二十多遍。。因?yàn)闆](méi)綁定bind
應(yīng)該這樣寫(xiě)?。?/p>

不帶參的:
<i className="plus iconfont icon-jiahao" onClick={this.deltocartFn}></i>
帶參的:
<i className="plus iconfont icon-jiahao" onClick={this.addtocartFn.bind(this, item)}></i>

8.動(dòng)態(tài)className

 <i className={"plus iconfont icon-jiahao "+(item.num!=0?"none":"block")} ></i>
 <i className={"del iconfont icon-jiahao "+(item.num==0?"none":"block")} ></i>

9.table的用法:
以下這種是會(huì)報(bào)錯(cuò)的,必須由tbody包含

 <table>
                        <tr>
                            <td></td>
                        </tr>
</table>

10.公共方法引用
common.js:

import  'whatwg-fetch'
import {toggleloading} from './../redux/action/layer'

expor const sampleFn = ()=>{

}

export const fetchPosts = (postTitle,Fn) => (dispatch, getState) => {
    dispatch(toggleloading(true));
    return fetch(postTitle)
        .then(response => response.json())
        .then(json => {
            setTimeout(()=>{
                dispatch(toggleloading(false));
                return Fn(json);
            },1000)
        });
}

普通公共方法就直接應(yīng)用就可以了,異步action方法需要在mapDispatchToProps函數(shù)中注入需要使用的公共方法

引用到頁(yè)面:

import {fetchPosts,sampleFn} from '../../lib/common'

class Shop extends Component{
    componentWillMount(){

        sampleFn();

        this.props.fetchPosts('/api/data.json',(res)=>{
            this.props.getgoodlist(res.data.songs);
        })
    }

  render(){
      return(
          ...
        )
      }
}

const mapStateToProps = (state) =>({
   ...
})
const mapDispatchToProps = (dispatch) =>({
    ...
    fetchPosts:(url,fn)=>dispatch(fetchPosts(url,fn))
})

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

11.報(bào)錯(cuò)Proxy error
本來(lái)用的好好的,今早起來(lái)發(fā)現(xiàn)數(shù)據(jù)無(wú)法獲取

Proxy error: Could not proxy request /api/data.json from localhost:3000 to localhost:5000 (ENOTFOUND).

找到占用5000端口的pid

netstat -aon|findstr “7000”
image.png

14112就是node.exe,找到592就是金山詞霸。。。額,金山詞霸右鍵點(diǎn)擊結(jié)束進(jìn)程


image.png

但還是不行,我改了一下proxy

"proxy": {
    "/api": {
      "target": "http://192.168.31.1:5000"  //這兒以前是 "http://localhost:5000
"
    }
  }

就好了
12.返回頁(yè)面
這個(gè)除了Link標(biāo)簽以外當(dāng)然也需要點(diǎn)擊返回或跳轉(zhuǎn)了

this.props.history.push('/shop')    返回指定頁(yè)面
this.props.history.goBack()  返回上一頁(yè)
this.props.history.go(-2)   返回上上一頁(yè)

這幾個(gè)方法不會(huì)刷新目標(biāo)頁(yè),但是都會(huì)觸發(fā)目標(biāo)頁(yè)面的componentWillMount()

13.定時(shí)器
一進(jìn)來(lái)定時(shí)器就啟動(dòng),返回首頁(yè)時(shí)停止。這個(gè)this.interval屬于該class的全局方法,不止可以在 componentDidMount()中定義,也可以在方法中定義,因?yàn)槲覀円矔?huì)有點(diǎn)擊按鈕啟動(dòng)定時(shí)器的業(yè)務(wù)場(chǎng)景

    componentDidMount() {
        this.interval = setInterval(() => this.tick(), 1000);
    }
    tick=()=>{
        console.log('kk--');
    }
    goShopIndex=()=>{
        clearInterval(this.interval);
        this.props.history.goBack()
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容